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)

macro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; input_inner ! { iter , $ ( $ r ) * } } ; ( iter = $ iter : ident , $ ( $ r : tt ) * ) => { let s = { use std :: io :: Read ; let mut s = String :: new ( ) ; std :: io :: stdin ( ) . read_to_string ( & mut s ) . unwrap ( ) ; s } ; let mut $ iter = s . split_whitespace ( ) ; input_inner ! { $ iter , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let s = { use std :: io :: Read ; let mut s = String :: new ( ) ; std :: io :: stdin ( ) . read_to_string ( & mut s ) . unwrap ( ) ; s } ; let mut iter = s . split_whitespace ( ) ; input_inner ! { iter , $ ( $ r ) * } } ; }
macro_rules ! input_inner { ( $ iter : expr ) => { } ; ( $ iter : expr , ) => { } ; ( $ iter : expr , mut $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let mut $ var = read_value ! ( $ iter , $ t ) ; input_inner ! { $ iter $ ( $ r ) * } } ; ( $ iter : expr , mut $ var : ident $ ( $ r : tt ) * ) => { input_inner ! { $ iter , mut $ var : usize $ ( $ r ) * } } ; ( $ iter : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ iter , $ t ) ; input_inner ! { $ iter $ ( $ r ) * } } ; ( $ iter : expr , $ var : ident $ ( $ r : tt ) * ) => { input_inner ! { $ iter , $ var : usize $ ( $ r ) * } } ; }
macro_rules ! read_value { ( $ iter : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ iter , $ t ) ) ,* ) } ; ( $ iter : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ iter , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ iter : expr , { chars : $ base : expr } ) => { read_value ! ( $ iter , String ) . chars ( ) . map ( | c | ( c as u8 - $ base as u8 ) as usize ) . collect ::< Vec < usize >> ( ) } ; ( $ iter : expr , { char : $ base : expr } ) => { read_value ! ( $ iter , { chars : $ base } ) [ 0 ] } ; ( $ iter : expr , chars ) => { read_value ! ( $ iter , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ iter : expr , char ) => { read_value ! ( $ iter , chars ) [ 0 ] } ; ( $ iter : expr , usize1 ) => { read_value ! ( $ iter , usize ) - 1 } ; ( $ iter : expr , $ t : ty ) => { $ iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) } ; }
#[inline]
fn rmb(k: usize) -> usize {
    (k as isize & -(k as isize)) as usize
}
pub trait Monoid {
    type T: Clone + PartialEq;
    fn mempty(&self) -> Self::T;
    fn mappend(&self, x: &Self::T, y: &Self::T) -> Self::T;
}
pub struct BinaryIndexedTree<M: Monoid> {
    bit: Vec<M::T>,
    m: M,
}
impl<M: Monoid> BinaryIndexedTree<M> {
    pub fn new(n: usize, m: M) -> BinaryIndexedTree<M> {
        let bit = vec![m.mempty(); n + 1];
        BinaryIndexedTree { bit: bit, m: m }
    }
    #[doc = " 1-indexed"]
    pub fn query(&self, k: usize) -> M::T {
        let mut res = self.m.mempty();
        let mut k = k;
        while k > 0 {
            res = self.m.mappend(&res, &self.bit[k]);
            k -= rmb(k);
        }
        res
    }
    #[doc = " 1-indexed"]
    pub fn update(&mut self, k: usize, x: M::T) {
        let mut k = k;
        while k < self.bit.len() {
            self.bit[k] = self.m.mappend(&self.bit[k], &x);
            k += rmb(k);
        }
    }
}
impl<M: Monoid> BinaryIndexedTree<M>
where
    M::T: Ord,
{
    #[doc = " 1-indexed"]
    pub fn lower_bound(&self, x: M::T) -> (usize, M::T) {
        let n = self.bit.len() - 1;
        let mut acc = self.m.mempty();
        let mut pos = 0;
        let mut k = 1 << format!("{:b}", n).len();
        while k > 0 {
            if k + pos <= n && self.m.mappend(&acc, &self.bit[k + pos]) < x {
                pos += k;
                acc = self.m.mappend(&acc, &self.bit[pos]);
            }
            k >>= 1;
        }
        (pos + 1, acc)
    }
}
pub struct AnyMonoid<T: Clone, F: Fn(&T, &T) -> T> {
    id: T,
    op: F,
}
impl<T: Clone, F: Fn(&T, &T) -> T> AnyMonoid<T, F> {
    pub fn new(id: T, op: F) -> AnyMonoid<T, F> {
        AnyMonoid { id: id, op: op }
    }
}
impl<T: Clone + PartialEq, F: Fn(&T, &T) -> T> Monoid for AnyMonoid<T, F> {
    type T = T;
    fn mempty(&self) -> T {
        self.id.clone()
    }
    fn mappend(&self, x: &T, y: &T) -> T {
        (self.op)(x, y)
    }
}
use std::cmp::Ordering;
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct Rev<T>(pub T);
impl<T: PartialOrd> PartialOrd for Rev<T> {
    fn partial_cmp(&self, other: &Rev<T>) -> Option<Ordering> {
        other.0.partial_cmp(&self.0)
    }
}
impl<T: Ord> Ord for Rev<T> {
    fn cmp(&self, other: &Rev<T>) -> Ordering {
        other.0.cmp(&self.0)
    }
}
fn main() {
    input! { n, p: [usize; n] };
    let mut v = (0..n).map(|i| i + 2).collect::<Vec<_>>();
    v.sort_by_key(|&i| Rev(p[i - 2]));
    let mut bit = BinaryIndexedTree::new(n + 2, AnyMonoid::new(0, |&x, &y| x + y));
    let mut ans = 0;
    bit.update(1, 1);
    bit.update(n + 2, 1);
    for &i in &v {
        bit.update(i, 1);
        let x = bit.query(i);
        let l = bit.lower_bound(x - 1).0;
        let r = bit.lower_bound(x + 1).0;
        if l > 1 {
            ans += p[i - 2] * (l - bit.lower_bound(x - 2).0) * (r - i);
        }
        if r < n + 2 {
            ans += p[i - 2] * (bit.lower_bound(x + 2).0 - r) * (i - l);
        }
    }
    println!("{}", ans);
}