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.42.0) (judge verdict: Accepted)

//use itertools::Itertools;
use std::cmp;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::io::Read;
use std::usize::MAX;

macro_rules! input {(source = $s:expr, $($r:tt)*) => {let mut iter = $s.split_whitespace();let mut next = || { iter.next().unwrap() };input_inner!{next, $($r)*}};($($r:tt)*) => {let stdin = std::io::stdin();let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));let mut next = move || -> String{bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect()};input_inner!{next, $($r)*}};}
macro_rules! input_inner {($next:expr) => {};($next:expr, ) => {};($next:expr, $var:ident : $t:tt $($r:tt)*) => {let $var = read_value!($next, $t);input_inner!{$next $($r)*}};}
macro_rules! read_value {($next:expr, ( $($t:tt),* )) => {( $(read_value!($next, $t)),* )};($next:expr, [ $t:tt ; $len:expr ]) => {(0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()};($next:expr, chars) => {read_value!($next, String).chars().collect::<Vec<char>>()};($next:expr, usize1) => {read_value!($next, usize) - 1};($next:expr, [ $t:tt ]) => {{let len = read_value!($next, usize);(0..len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()}};($next:expr, $t:ty) => {$next().parse::<$t>().expect("Parse error")};}

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

    let mut num_index = vec![0; n + 1];
    for i in 0..n {
        num_index[p[i]] = i;
    }

    let mut ans = 0;

    let mut big_num_induces = BTreeSet::new();
    // 一番大きい数を入れておく
    big_num_induces.insert(num_index[n]);

    for i in (1..n).rev() {
        // 自分のインデックス
        let index = num_index[i];

        let mut before_induces = big_num_induces.range(..index).rev();
        let mut after_induces = big_num_induces.range(index..);

        // 自分よりすぐ前にある、自分より大きいやつ
        let greater_front = match before_induces.next() {
            Some(&b) => b as isize,
            None => -1,
        };

        // greater_frontよりすぐ前にある、自分より大きいやつ
        let greater_front_front = match before_induces.next() {
            Some(&b) => b as isize,
            None => -1,
        };

        // 自分よりすぐ後ろにある、自分より大きいやつ
        let greater_back = match after_induces.next() {
            Some(&a) => a as isize,
            None => n as isize,
        };

        // greater_backよりすぐ後ろにある、自分より大きいやつ
        let greater_back_back = match after_induces.next() {
            Some(&a) => a as isize,
            None => n as isize,
        };

        /*
        println!(
            "{} {} {} {} {}",
            greater_front_front, greater_front, index, greater_back, greater_back_back
        );
        */

        // 自分とgreater_frontを含み、greater_backを含まないものの総数*自分
        // ff(...f...i...)b...bb の数。 ff...fでは0個からffの直前まで採用でき、i...bでは0個からbの直前まで採用できる
        ans += (greater_front - greater_front_front) * (greater_back - index as isize) * i as isize;

        // 自分とgreater_backを含み、greater_frontを含まないものの総数*自分
        ans += (greater_back_back - greater_back) * (index as isize - greater_front) * i as isize;

        // 最後にこのループで考慮したインデックスを考慮済みインデックスにいれる
        big_num_induces.insert(index);
    }

    println!("{}", ans);
}

fn main() {
    let thd = std::thread::Builder::new().stack_size(104_857_600);
    thd.spawn(|| solve()).unwrap().join().unwrap();

    /*
    // 入力を一括で読み込む場合
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();
    let mut input = buf.split_whitespace();

    // inputに対しnext()で読み込んでいく
    let q: usize = input.next().unwrap().parse().unwrap();
    */
}

const LARGE_PRIME: u64 = 1_000_000_007;

// @〜でsnippet