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();
        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)*}
    };

    ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $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, [ $t:tt ]) => {
        {
            let len = read_value!($next, usize);
            (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:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_imports)]
use std::cmp::{min, max};

fn main() {
    input!{
        n: usize,
        v: [usize1; n]
    }
    let pre = search(n, &v);
    let mut vr = v.clone();
    vr.reverse();
    let pos = search(n, &vr);
    let mut ans = 0;
    for i in 0..n {
        ans += pre[i].1 * pos[i].0 * (i + 1);
        ans += pos[i].1 * pre[i].0 * (i + 1);
    }
    println!("{}", ans);
}

fn search(n: usize, v: &Vec<usize>) -> Vec<(usize, usize)> {
    let mut ret = vec![(0, 0); n];
    let mut segt = LSegT::new(n);
    for i in 0..n {
        let (a, b) = segt.get(v[i]);
        ret[v[i]].0 = (i as i64 - a) as usize;
        ret[v[i]].1 = (a - b) as usize;
        segt.update(0, v[i], i as i64);
    }
    ret
}

struct LSegT {
    v: Vec<(i64, i64)>,
    lazy: Vec<(i64, i64)>,
    n: usize
}

impl LSegT {
    fn new(n: usize) -> LSegT {
        let mut s = 1;
        while s < n {
            s *= 2;
        }
        LSegT{v: vec![(-1, -1); 2 * s - 1], lazy: vec![(-1, -1); 2 * s - 1], n: s}
    }

    fn eval(&mut self, p: usize) {
        if self.lazy[p] == (-1, -1) {
            return;
        }
        if self.v[p].0 > self.lazy[p].0 {
            self.v[p].1 = max(self.v[p].1, self.lazy[p].0);
        } else if self.v[p].0 == self.lazy[p].0 {
            self.v[p].1 = max(self.v[p].1, self.lazy[p].1);
        } else {
            self.v[p].1 = max(self.v[p].0, self.lazy[p].1);
            self.v[p].0 = self.lazy[p].0;
        }
        if p < self.n - 1 {
            if self.lazy[2 * p + 1].0 > self.lazy[p].0 {
                self.lazy[2 * p + 1].1 = max(self.lazy[2 * p + 1].1, self.lazy[p].0);
            } else if self.lazy[2 * p + 1].0 == self.lazy[p].0 {
                self.lazy[2 * p + 1].1 = max(self.lazy[2 * p + 1].1, self.lazy[p].1);
            } else {
                self.lazy[2 * p + 1].1 = max(self.lazy[2 * p + 1].0, self.lazy[p].1);
                self.lazy[2 * p + 1].0 = self.lazy[p].0;
            }
            if self.lazy[2 * p + 2].0 > self.lazy[p].0 {
                self.lazy[2 * p + 2].1 = max(self.lazy[2 * p + 2].1, self.lazy[p].0);
            } else if self.lazy[2 * p + 2].0 == self.lazy[p].0 {
                self.lazy[2 * p + 2].1 = max(self.lazy[2 * p + 2].1, self.lazy[p].1);
            } else {
                self.lazy[2 * p + 2].1 = max(self.lazy[2 * p + 2].0, self.lazy[p].1);
                self.lazy[2 * p + 2].0 = self.lazy[p].0;
            }
        }
        self.lazy[p] = (-1, -1);
    }

    fn update(&mut self, l: usize, r: usize, x: i64) {
        let n = self.n;
        self.update_rec(l, r, x, 0, 0, n - 1);
    }

    fn update_rec(&mut self, l: usize, r: usize, x: i64, p: usize, pl: usize, pr: usize) {
        self.eval(p);
        if pl > r || pr < l {
            return;
        } else if l <= pl && pr <= r {
            if x != self.lazy[p].0 {
                self.lazy[p].1 = self.lazy[p].0;
                self.lazy[p].0 = x;
            }
            self.eval(p);
        } else {
            self.update_rec(l, r, x, 2 * p + 1, pl, (pl + pr - 1) / 2);
            self.update_rec(l, r, x, 2 * p + 2, (pl + pr + 1) / 2, pr);
        }
    }

    fn get(&mut self, l: usize) -> (i64, i64) {
        let n = self.n;
        self.get_rec(l, 0, 0, n - 1)
    }

    fn get_rec(&mut self, l: usize, p: usize, pl: usize, pr: usize) -> (i64, i64) {
        self.eval(p);
        if pl > l || pr < l {
            (-1, -1)
        } else if l == pl && pr == l {
            self.v[p]
        } else if l <= (pl + pr - 1) / 2 {
            self.get_rec(l, 2 * p + 1, pl, (pl + pr - 1) / 2)
        } else {
            self.get_rec(l, 2 * p + 2, (pl + pr + 1) / 2, pr)
        }
    }
}