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:
/*
#[allow(unused_imports)]
use std::io::Write;
use std::collections::BTreeSet;
use std::ops::Bound::*;
use proconio::input;

fn main() {
    input! {
        n: usize,
        p: [usize; n],
    }

    let mut index = vec![0; n + 1];
    for (i, x) in p.iter().enumerate() {
        index[*x] = i + 1; // 1-based
    }

    // 使わないのでdrop
    drop(p);

    let mut calc = vec![0; n + 1];

    let mut set = BTreeSet::new();
    // 番兵
    set.insert(0);
    set.insert(0);
    set.insert(n + 1);
    set.insert(n + 1);
    for a in (1..=n).rev() {
        let i_a = index[a];

        // 左側
        // for x in set.range((Unbounded, Excluded(i_a))).rev() {
        //     eprintln!("{:?}", x);
        // }
        let mut l_range = set.range((Unbounded, Excluded(i_a))).rev();
        let i_l1 = l_range.next().unwrap();
        let i_l2 = match l_range.next() {
            Some(x) => *x,
            None => 0,
        };
        // eprintln!("l: {}, {}", i_l1, i_l2);

        // 右側
        let mut r_range = set.range((Excluded(i_a), Unbounded));
        let i_r1 = r_range.next().unwrap();
        let i_r2 = match r_range.next() {
            Some(x) => *x,
            None => n + 1,
        };
        // eprintln!("r: {}, {}", i_r1, i_r2);

        calc[a] += (i_l1 - i_l2) * (i_r1 - i_a);
        calc[a] += (i_a - i_l1)* (i_r2 - i_r1);

        set.insert(i_a);
    }

    // eprintln!("{:?}", calc);

    let mut ans = 0;
    for a in 1..=n {
        ans += a * calc[a];
    }
    println!("{}", ans);
}

*/

fn main() {
    let exe = "/tmp/binA476AB9A";
    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>";