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: Wrong Answer)

// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        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, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($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) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

fn solve(n: usize, p: Vec<u32>) -> usize {
  // indexes[num] is index of num in p
  let mut indexes = vec![0; n + 1];
  // prevs[i] is the previous non-calculated index of i
  let mut prevs: Vec<_> = (0..n + 2).map(|n| if n == 0 { 0 } else {n - 1}).collect();
  // nexts[i] is the next non-calculated index of i
  let mut nexts: Vec<_> = (0..n + 2).map(|n| n + 1).collect();

  prevs[n + 1] = n;
  nexts[0] = 1;

  for i in 0..n {
    indexes[p[i] as usize] = i + 1;
  }

  let mut ans = 0;
  for num in 1..n {
    let index = indexes[num];
    // prev is the previous index
    let prev = prevs[index];
    // next is the next index
    let next = nexts[index];

    // count with some conditions
    if 0 < prev { // number bigger than num is in nexts
      ans += num * (prev - prevs[prev]) * (next - index);
    }
    // number bigger than num is in prevs
    if next != n + 1 {
      ans += num * (index - prev) * (nexts[next] - next);
    }
    println!("num: {} index: {} prev: {} next: {} ans: {}", num, index, prev, next, ans);

    // concat prev and next to mark as calculated
    nexts[prev] = next;
    prevs[next] = prev;
  }
  ans
}

fn main() {
  input! {
    n: usize,
    p: [u32; n]
  };

  println!("{}", solve(n, p));
}