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: Time Limit Exceeded)

use std::ops;

fn read_line() -> String {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim_right().to_owned()
}

fn to_vec(s: String, offset: u64) -> Vec<u64> {
    s.split_whitespace()
        .map(|s| s.parse::<u64>().unwrap() - offset)
        .collect()
}

trait Center {
    fn center(&self) -> usize;
    fn split(&self) -> (ops::Range<usize>, ops::Range<usize>);
}

impl Center for ops::Range<usize> {
    fn center(&self) -> usize {
        self.start + self.len() / 2
    }

    fn split(&self) -> (ops::Range<usize>, ops::Range<usize>) {
        let c = self.center();
        (self.start..c, c..self.end)
    }
}

trait BinarySearch {
    fn binary_search_position(&mut self, x: u64) -> usize;
    fn last2(&self) -> u64;
}

impl BinarySearch for Vec<u64> {
    fn binary_search_position(&mut self, x: u64) -> usize {
        let mut r = 0..self.len();
        while r.len() != 1 {
            let subs = r.split();
            r = if x < self[subs.0.end] as u64 {
                subs.0
            } else {
                subs.1
            };
        }
        if x < self[r.start] { r.start } else { r.end }
    }

    fn last2(&self) -> u64 {
        self[self.len() - 2]
    }
}

fn main() {
    read_line();
    let ps = to_vec(read_line(), 0);

    let mut total = 0;

    for i in 0..(ps.len() - 1) {
        let last_index = ps.len() - i - 1;
        let mut v = vec![ps[last_index]];
        for j in (0..last_index).rev() {
            let p = ps[j];
            let pos = v.binary_search_position(p);
            v.insert(pos, p);

            total += v.last2();
        }
    }

    println!("{}", total);
}