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 C++14 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include <bits/stdc++.h>
using namespace std;
//#define int long long

signed main() {
  int n;
  cin>>n;
  int p[n];
  for(int i=0;i<n;i++)cin>>p[i];
  int ans=0;
  priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> v;
  vector<pair<int,int>> l[n],r[n],at;
  int lx[n],rx[n];
  for(int i=0;i<n;i++){lx[i]=-1;rx[i]=n;}
  for(int i=0;i<n;i++){
    while(!v.empty()&&v.top().first<p[i]){
      l[i].push_back(v.top());
      rx[v.top().second]=i;
      v.pop();
    }
    v.push(make_pair(p[i],i));
  }
  while(!v.empty())v.pop();
  for(int i=n-1;i>=0;i--){
    while(!v.empty()&&v.top().first<p[i]){
      r[i].push_back(v.top());
      lx[v.top().second]=i;
      v.pop();
    }
    v.push(make_pair(p[i],i));
  }
  int a,b;
  for(int i=0;i<n;i++){
    l[i].push_back(make_pair(0,lx[i]));
    r[i].push_back(make_pair(0,rx[i]));
  }
 
  for(int i=0;i<n;i++){
    a=l[i].size()-2;b=r[i].size()-2;
    while(a>=0||b>=0){
      //cerr<<ans<<' '<<a<<' '<<b<<endl;
      if(a<0){
        ans-=(l[i][a+1].second-i)*(r[i][b+1].second-r[i][b].second)*r[i][b].first;
         b--;
         continue;
      }
      if(b<0){
        ans-=(l[i][a+1].second-l[i][a].second)*(r[i][b+1].second-i)*l[i][a].first;
        a--;
        continue;
      }
      if(l[i][a].first>r[i][b].first){
        ans-=(l[i][a+1].second-l[i][a].second)*(r[i][b+1].second-i)*l[i][a].first;
        a--;
      }else{
         ans-=(l[i][a+1].second-i)*(r[i][b+1].second-r[i][b].second)*r[i][b].first;
         b--;
      }
    }
  }
  cout<<ans;
  

    return 0;
}