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)

#[allow(unused_imports)]
use std::cmp::{Ordering};

#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};

#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, Write};

#[allow(unused_imports)]
use std::iter::FromIterator;

#[allow(unused_macros)]
macro_rules! min {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::min($x, min!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! max {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::max($x, max!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! get { 
    ([$t: ty]) => { 
        { 
            let mut line = String::new(); 
            stdin().read_line(&mut line).unwrap(); 
            line.split_whitespace().map(|t|t.parse::<$t>().unwrap()).collect::<Vec<_>>()
        }
    };
    ([$t: ty];$n: expr) => {
        (0..$n).map(|_|get!([$t])).collect::<Vec<_>>()
    };
    ($t: ty) => {
        {
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            line.trim().parse::<$t>().unwrap()
        }
    };
    ($($t: ty),*) => {
        { 
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            ($(iter.next().unwrap().parse::<$t>().unwrap(),)*)
        }
    };
    ($t: ty; $n: expr) => {
        (0..$n).map(|_|get!($t)).collect::<Vec<_>>()
    };
    ($($t: ty),*; $n: expr) => {
        (0..$n).map(|_|get!($($t),*)).collect::<Vec<_>>()
    };
}

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

const BIG_STACK_SIZE: bool = true;

#[allow(dead_code)]
fn main() {
    use std::thread;
    if BIG_STACK_SIZE {
        thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .name("solve".into())
            .spawn(solve)
            .unwrap()
            .join()
            .unwrap();
    } else {
        solve();
    }
}

struct Bit {
    tree: Vec<isize>,
}
impl Bit {
#[allow(dead_code)]
    fn new(n: usize) -> Self {
        Bit { tree: vec![0; n] }
    }
#[allow(dead_code)]
    fn from(vec: Vec<isize>) -> Self {
        let mut bit = Bit::new(vec.len() + 1);
        for i in 1..(vec.len() + 1) {
            bit.add(i, vec[i - 1]);
        }
        bit
    }
#[allow(dead_code)]
    fn add(&mut self, a: usize, w: isize) {
        let mut x = a as isize;
        while x < self.tree.len() as isize {
            self.tree[x as usize] += w;
            x += x & (-x);
        }
    }
#[allow(dead_code)]
    fn sum(&self, n: usize) -> isize {
        let mut x = n as isize;
        let mut ret = 0;
        while x > 0 {
            ret += self.tree[x as usize];
            x -= x & (-x);
        }
        ret
    }
#[allow(dead_code)]
    fn sum_with(&self, l: usize, r: usize) -> isize {
        self.sum(r) - self.sum(l - 1)
    }
}

trait Indexable {
    type Output;
    fn index(&self, i: usize) -> Self::Output;
}

impl Indexable for Bit {
    type Output = isize;

    fn index(&self, i: usize) -> Self::Output {
        self.sum(i)
    }
}

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

trait ExactSize {
    fn len(&self) -> usize;
}

impl ExactSize for Bit {
    fn len(&self) -> usize {
        self.tree.len()
    }
}

impl<T: Ord, U> BinarySearch<T> for U 
    where U: Indexable<Output=T> + ExactSize {
#[allow(dead_code)]
    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.index(mid).cmp(x) {
                Ordering::Less => {
                    low = mid + 1;
                }
                Ordering::Equal | Ordering::Greater => {
                    high = mid;
                }
            }
        }
        low
    }
#[allow(dead_code)]
    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.index(mid).cmp(x) {
                Ordering::Less | Ordering::Equal => {
                    low = mid + 1;
                }
                Ordering::Greater => {
                    high = mid;
                }
            }
        }
        low
    }
}

fn solve() {
    let n = get!(usize);
    let p = get!([usize]);

    let mut pinv = vec![0; n+1];
    let mut bit = Bit::new(n+3);
    for i in 0..n {
        pinv[p[i]] = i+2;
    }
    let mut res = 0;
    bit.add(1,1);
    bit.add(1,1);
    bit.add(n+2,1);
    bit.add(n+2,1);
    for i in (1..n+1).rev() {
        let pos = pinv[i];
        let posnum = bit.sum(pos);
        let ll = bit.lower_bound(&(posnum-1));
        let l = bit.lower_bound(&(posnum));
        let r = bit.lower_bound(&(posnum+1));
        let rr = bit.lower_bound(&(posnum+2));
        res += ((rr-r)*(pos-l)+(r-pos)*(l-ll))*i;
        bit.add(pos,1);
    }
    println!("{}",res);
}