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)

#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(non_upper_case_globals)]


macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut 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<_>>()
    };

    ($next:expr, [$t:tt]) => {
        {
            let len = read_value!($next, usize);
            (0..len).map(|_| read_value!($next, $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")
    };
}


#[cfg(debug_assertions)]
macro_rules! mydbg {
    //($arg:expr) => (dbg!($arg))
    ($arg:expr) => (println!("{:?}",$arg));
}


#[cfg(not(debug_assertions))]
macro_rules! mydbg {
    ($($arg:expr),*) => {};
}


use std::cmp;
use std::collections::HashMap;



use std::ops::{ Add, Sub , Div , Mul };
static global_mod : i64 = 1000000007;

#[derive(Debug,Copy,Clone)]
pub struct ModInt {
    x : i64
}

impl ModInt{
    pub fn  new (p:i64) -> Self {
        let a = (p % global_mod + global_mod)% global_mod;     
        return ModInt{x:a};
    }

    pub fn inv (self) -> Self{
        return self.pow(global_mod-2);

    }

    pub fn pow (self , t:i64) -> Self{
        if(t==0 ) {return ModInt::new(1)};
        let mut a = self.pow(t>>1);
        a = a*a;
        if(t&1 != 0) {a = a* self};
        return a;
    }
}
impl Add for ModInt {
    type Output = ModInt;
    fn add(self,other : ModInt) -> ModInt{
        let ret  = self.x + other.x ;
        return ModInt::new(ret);
    }
}
impl Sub for ModInt {
    type Output = ModInt;
    fn sub(self,other : ModInt) -> ModInt{
        let ret  = self.x - other.x;
        return ModInt::new(ret);
    }
}
impl Mul for ModInt {
    type Output = ModInt;
    fn mul(self,other : ModInt) -> ModInt{
        let ret  = self.x * other.x ;
        return ModInt::new(ret);
    }
}

impl Div for ModInt {
    type Output = ModInt;
    fn div(self,other : ModInt) -> ModInt{
        let ret  = self.x * other.inv().x;
       return ModInt::new(ret);
    }
}

impl std::string::ToString for ModInt{
    fn to_string(&self) -> String{
        return self.x.to_string();
    }
}


pub struct Combination{
    fact : Vec<ModInt>,
    ifact : Vec<ModInt>
}

impl Combination{
    pub fn new(n:i32)->Self{
        let mut fact = vec![ModInt::new(0);(n+1) as usize];
        let mut ifact = vec![ModInt::new(0);(n+1) as usize];
        fact[0] = ModInt::new(1);
        for i in 1..n+1 { fact[i as usize] = fact[(i-1) as usize] * ModInt::new(i as i64) };
        ifact[n as usize] = fact[n as usize].inv();
        for i in (1..n+1).rev(){ ifact[(i-1) as usize] = ifact[i as usize]* ModInt::new(i as i64) }


        let a = Combination{
            fact : fact,
            ifact : ifact
        };
        return a;
    }

    pub fn gen(self , n:i32 , k:i32)-> ModInt{
        mydbg!(self.fact[n as usize]);
        mydbg!(self.ifact[k as usize]);
        mydbg!(self.ifact[(n-k) as usize]);
        if (k < 0 || k > n) {return ModInt::new(0 as i64)};
        return self.fact[n as usize]*self.ifact[k as usize]*self.ifact[(n-k) as usize];

    }
}


pub struct SegTree{
    n : i32,
    data : Vec<(i64,i64)>,
}
impl SegTree{
    pub fn new(n_:i32) ->Self{
        let MAX_N = 1e6 as usize;
        let mut n = 1;
        let mut data = vec![(0,0);(2*MAX_N)];
        while (n < n_){
            n*=2;
        }
        for i in 0..(2*n-1){
            data[i as usize] = (-10000,-10000);
        }
        
        return SegTree{
            n : n,
            data :data
        };

    }

    pub fn update(&mut self , k:i32,a:i64){
        let mut k = k + (self.n as i32)-1;
        self.data[k as usize]  = (a,-10000);
        while(k>0){
            k = (k-1)/2;
            let (x,y) = self.data[(k*2+1) as usize];
            let (v,w) = self.data[(k*2+2) as usize];
            let mut tmp = vec![x,y,v,w];
            tmp.sort();
            self.data[k as usize] = (tmp[3] , tmp[2]);
        }
    }

    pub fn query (&mut self , a:i32, b:i32 , k:i32 ,l:i32,r:i32)->(i64,i64){
        let mut r = if(r<0) {self.n} else {r};
        if(r <= a || b<= l) {return (0,0)}
        if(a<= l && r<= b) {return self.data[k as usize]}
        else{
            let (x,y) = self.query(a,b,k*2+1,l,(l+r)/2);
            let (v,w) = self.query(a,b,k*2+2,(l+r)/2,r);
            let mut tmp = vec![x,y,v,w];
            tmp.sort();
            return (tmp[3] , tmp[2]);
        }
    }
    


}



fn main() {


    input! { 
       n: usize,
       p : [i64;n],
    }



    let mut seg = SegTree::new(n as i32);
    for i in 0..n{
        seg.update(i as i32, p[i]);
    }

   
   


    let mut ans = 0;
    for i in 0..n-1{
        for j in (i+1)..n{
            let tmp = seg.query(i as i32, (j+1) as i32, 0, 0, -1);
            ans += if(tmp.1 ==0 ){tmp.0 }else{tmp.1};
            mydbg!((i,j));
            mydbg!(tmp);
        }
    }
    
    
    println!("{}",ans);


}