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(dead_code)]
fn solve(src: &str) -> String {
    let mut sc = Scanner::from_str(src);

    let n: usize = sc.read();
    // idx[p[i]] = i
    let idx = {
        let mut idx: Vec<usize> = vec![0; n];
        for i in 0..n {
            let p: usize = sc.read();
            idx[p - 1] = i;
        }
        idx
    };

    let mut p_i = 0;

    // l_i[j] = max{k| k<j, p[k]>p_i}
    // r_i[j] = min{k| k>j, p[k]>p_i}
    let mut l_i: Vec<_> = vec![None];
    l_i.extend((0..n - 1).map(Some));
    let mut r_i: Vec<_> = (1..n).map(Some).collect();
    r_i.push(None);

    let mut ans = 0;
    while p_i < n {
        let i = idx[p_i];

        let (l, l2) = {
            if let Some(l) = l_i[i] {
                if let Some(l2) = l_i[l] {
                    (l as isize, l2 as isize)
                } else {
                    (l as isize, -1)
                }
            } else {
                (-1, -1)
            }
        };

        let (r, r2) = {
            if let Some(r) = r_i[i] {
                if let Some(r2) = r_i[r] {
                    (r as isize, r2 as isize)
                } else {
                    (r as isize, n as isize)
                }
            } else {
                (n as isize, n as isize)
            }
        };

        let i = i as isize;
        let c_i = (l - l2) * (r - i) + (r2 - r) * (i - l);
        ans += (p_i + 1) * c_i as usize;

        p_i += 1;

        // l_i <- l_(idx[p_i+1])
        // r_i <- r_(idx[p_i+1])
        if l >= 0 {
            r_i[l as usize] = r_i[i as usize]
        }
        if r < n as isize {
            l_i[r as usize] = l_i[i as usize]
        }
    }

    format!("{}\n", ans)
}
#[test]
fn test_solve() {
    assert_eq!(solve("3\n2 3 1\n"), "5\n");
    assert_eq!(solve("5\n1 2 3 4 5\n"), "30\n");
    assert_eq!(solve("8\n8 2 7 3 4 5 6 1\n"), "136\n");
}
fn main() {
    let mut buf = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut buf).unwrap();
    use std::io::Write;
    std::io::stdout().write_all(solve(&buf).as_bytes()).unwrap();
}
struct Scanner<I> {
    src: I,
}
impl<'a> Scanner<std::str::SplitWhitespace<'a>> {
    fn from_str(src: &'a str) -> Self {
        Scanner {
            src: src.split_whitespace(),
        }
    }
}
impl<'a, I> Scanner<I>
where
    I: std::iter::Iterator<Item = &'a str>,
{
    fn read<T: std::str::FromStr>(&mut self) -> T {
        self.src.next().unwrap().parse().ok().expect("Parse error")
    }
}