Problem:
Score: 500 points

Problem Statement

Given is a permutation P of \{1, 2, \ldots, N\}.

For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.

Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Constraints

2 \le N \le 10^5

1 \le P_i \le N

P_i \neq P_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N

Output

Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input 1

3
2 3 1

Sample Output 1

5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

30

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

136

Solution in Rust (1.15.1) (judge verdict: Accepted)

// This code is generated by [cargo-atcoder](https://github.com/tanakh/cargo-atcoder)
// Original source code:
/*
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;

fn main() {
    input! {
        n: usize,
        p: [Usize1; n],
    }
    // 2 4 3 1 5
    //
    let mut idx = vec![0; n];
    for i in 0..n {
        idx[p[i]] = i + 1;
    }

    let mut m = std::collections::BTreeSet::new();
    m.insert(idx[n - 1]);
    let mut res = 0;
    for i in (0..n - 1).rev() {
        use std::ops::Bound::*;
        let mut up = m.range((Excluded(idx[i]), Unbounded));
        let mut lo = m.range((Unbounded, Excluded(idx[i])));
        let mut up2 = up.clone();
        up2.next();
        let mut lo2 = lo.clone();
        lo2.next_back();

        let up = *up.next().unwrap_or(&(n + 1));
        let up2 = *up2.next().unwrap_or(&(n + 1));
        let lo = *lo.next_back().unwrap_or(&0);
        let lo2 = *lo2.next_back().unwrap_or(&0);

        // println!(
        //     "{} {}*{} + {}*{}",
        //     i + 1,
        //     up - idx[i],
        //     lo - lo2,
        //     up2 - up,
        //     idx[i] - lo
        // );
        res += (i + 1) * ((up - idx[i]) * (lo - lo2) + (up2 - up) * (idx[i] - lo));
        m.insert(idx[i]);
    }
    println!("{}", res);
}
*/

fn main() {
    let exe = "/tmp/bin08A176C1";
    std::io::Write::write_all(&mut std::fs::File::create(exe).unwrap(), &decode(BIN)).unwrap();
    std::fs::set_permissions(exe, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
    std::process::exit(std::process::Command::new(exe).status().unwrap().code().unwrap())
}

fn decode(v: &str) -> Vec<u8> {
    let mut ret = vec![];
    let mut buf = 0;
    let mut tbl = vec![64; 256];
    for i in 0..64 { tbl[TBL[i] as usize] = i as u8; }
    for (i, c) in v.bytes().filter_map(|c| { let c = tbl[c as usize]; if c < 64 { Some(c) } else { None } }).enumerate() {
        match i % 4 {
            0 => buf = c << 2,
            1 => { ret.push(buf | c >> 4); buf = c << 4; }
            2 => { ret.push(buf | c >> 2); buf = c << 6; }
            3 => ret.push(buf | c),
            _ => unreachable!(),
        }
    }
    ret
}

const TBL: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const BIN: &'static str = "<base64-encoded ELF executable removed>";