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)

#![allow(unused_imports)]
#![allow(non_snake_case)]
use std::cmp::*;
use std::collections::*;
use std::io::Write;
use std::ops::Bound::*;

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

fn main() {
    let n = read::<usize>();
    let p = read_vec::<i64>();

    let mut pairs = vec![];
    for i in 0..n {
        pairs.push((p[i], i));
    }
    pairs.sort();
    pairs.reverse();

    let poses_order = pairs.iter().map(|&x| x.1).collect::<Vec<_>>();
    let mut next_r = vec![n as i64; n];
    let mut next_l = vec![-1; n];
    let mut next_next_r = vec![n as i64; n];
    let mut next_next_l = vec![-1; n];

    let mut s = BTreeSet::new();
    for pos in poses_order {
        let mut after = s.range((Excluded(pos), Unbounded));
        if let Some(&x) = after.next() {
            next_r[pos] = x as i64;
            if let Some(&x) = after.next() {
                next_next_r[pos] = x as i64;
            }
        }
        let mut before = s.range((Unbounded, Excluded(pos))).rev();
        if let Some(&x) = before.next() {
            next_l[pos] = x as i64;
            if let Some(&x) = before.next() {
                next_next_l[pos] = x as i64;
            }
        }
        s.insert(pos);
    }
    debug!(next_r);
    debug!(next_l);

    let mut ans = 0;
    for i in 0..n {
        let temp;
        if next_l[i] == -1 && next_r[i] == n as i64 {
            temp = 0;
        } else if next_r[i] == n as i64 {
            temp = p[i] * (n - i) as i64 * (next_l[i] - next_next_l[i]);
        } else if next_l[i] == -1 {
            temp = p[i] * (i + 1) as i64 * (next_next_r[i] - next_r[i]);
        } else {
            let temp1 = p[i] * (i as i64 - next_l[i]) * (next_next_r[i] - next_r[i]);
            let temp2 = p[i] * (next_r[i] - i as i64) * (next_l[i] - next_next_l[i]);
            // debug!(temp1, temp2);
            temp = temp1 + temp2;
        }
        // ans += p[i] *
        //debug!(temp);
        ans += temp;
    }
    println!("{}", ans);
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

use std::cmp::Ordering;

pub trait BinarySearch<T> {
    fn lower_bound(&self, x: &T) -> usize;
    fn upper_bound(&self, x: &T) -> usize;
}

impl<T: Ord> BinarySearch<T> for [T] {
    fn lower_bound(&self, x: &T) -> usize {
        let mut low = 0;
        let mut high = self.len();

        while low != high {
            let mid = (low + high) / 2;
            match self[mid].cmp(x) {
                Ordering::Less => {
                    low = mid + 1;
                }
                Ordering::Equal | Ordering::Greater => {
                    high = mid;
                }
            }
        }
        low
    }

    fn upper_bound(&self, x: &T) -> usize {
        let mut low = 0;
        let mut high = self.len();

        while low != high {
            let mid = (low + high) / 2;
            match self[mid].cmp(x) {
                Ordering::Less | Ordering::Equal => {
                    low = mid + 1;
                }
                Ordering::Greater => {
                    high = mid;
                }
            }
        }
        low
    }
}