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)

use std::cmp;
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()
}

enum SortedType {
    Sorted,
    SortedReverse,
    Unsorted,
}

fn find_sorted_maxes(
    source: &Vec<u64>,
    a: usize,
    b: usize,
    to_index: &Vec<usize>,
) -> (u64, u64, SortedType) {
    let mut v: Vec<u64> = source[a..b].iter().cloned().collect();
    v.sort();

    let max = *v.last().unwrap();
    let max2 = v[v.len() - 2];

    let mut sorted = SortedType::Unsorted;

    (max, max2, sorted)
}

fn find_max2(a: u64, b: u64, c: u64) -> u64 {
    let mut v = vec![a, b, c];
    v.sort();
    v[v.len() - 2]
}

fn evaluate(v: &Vec<u64>, to_index: &Vec<usize>, r: &ops::Range<usize>) -> u64 {
    let n = r.len();
    if n < 2 {
        return 0;
    } else if n == 2 {
        return cmp::min(v[r.start], v[r.start + 1]) as u64;
    } else if n == 3 {
        let rs = r.start as u64;
        let (a, b, c) = (rs, rs + 1, rs + 2);
        let max2 = find_max2(a, b, c);
        return cmp::min(a, b) + cmp::min(b, c) + max2;
    }

    let (max, max2, maxes) = find_sorted_maxes(v, r.start, r.end, to_index);
    let (a, b, c) = {
        let a = to_index[max as usize];
        let b = to_index[max2 as usize];
        if a < b {
            split(r, a, b)
        } else {
            split(r, b, a)
        }
    };

    /*
    println!("{:?} = {:?} + {:?} - {:?}", r, a, b, c);
    print!("[{:?}, ", r.clone().map(|i| v[i]).collect::<Vec<_>>());
    print!("[{:?}, ", a.clone().map(|i| v[i]).collect::<Vec<_>>());
    println!("{:?}]", b.clone().map(|i| v[i]).collect::<Vec<_>>());
    println!("{:?}]", c.clone().map(|i| v[i]).collect::<Vec<_>>());
    println!("max2: {} * {} = {}", max2, max2_area / max2, max2_area);
    */

    let max2_area = (r.end as u64 - a.end as u64) * (b.start as u64 - r.start as u64) * max2;
    let a_e = evaluate(v, to_index, &a);
    let b_e = evaluate(v, to_index, &b);
    let dedup = evaluate(v, to_index, &c);

    let val = a_e + b_e + max2_area - dedup;
    //println!("{:?}: {}", r, val);
    val
}

fn split(
    v: &ops::Range<usize>,
    a: usize,
    b: usize,
) -> (ops::Range<usize>, ops::Range<usize>, ops::Range<usize>) {
    if v.len() == 3 {
        (v.start..(v.start + 2), (v.end - 2)..v.end, 0..0)
    } else {
        (v.start..b, (a + 1)..v.end, (a + 1)..b)
    }
}

fn main() {
    let n: usize = 1000; //read_line().parse().unwrap();
    let ps = (0..n).map(|i| i as u64).collect::<Vec<_>>(); //to_vec(read_line(), 1);

    let mut to_index = vec![0; n];
    for (i, &p) in ps.iter().enumerate() {
        to_index[p as usize] = i;
    }

    let mut val = evaluate(&ps, &to_index, &(0..ps.len()));
    val += (n * (n - 1) / 2) as u64;

    println!("{}, {}", val, (n - 1) * n * (2 * (n - 1) + 1) / 6);
}