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 (GCC 5.4.1) (judge verdict: Runtime Error)

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <limits.h>
int acs(const void *a, const void *b){return *(int*)a - *(int*)b;} /* 1,2,3,4.. */
int des(const void *a, const void *b){return *(int*)b - *(int*)a;} /* 8,7,6,5.. */
#define min(a,b) (a < b ? a: b)
#define max(a,b) (a > b ? a: b)

#define MAXN (1000)
#define MOD (998244353)


//グラフ
#define MAXV (MAXN*MAXN)
int Gv;
typedef struct edge
{
    int to;
    struct edge* next;
}edge;

edge* Ge[MAXV]; //vから出てる有向辺
int Gd[MAXV]; //vの次数

// vは頂点数、指定するときは0～(v-1)
void Ginit(int v)
{
    Gv = v;
}

void Gadd(int v, int to)
{
    edge* e = malloc(sizeof(edge));
    e->to = to;
    e->next = Ge[v];
    Ge[v] = e;
    Gd[v]++;
}

// 最長経路
// 閉路があれば-1
bool GLPvisit[MAXV];
bool GLPfixed[MAXV];
int GLP[MAXV];
int GLP_DFS(int v)
{
    if(GLPvisit[v])
    {
        return GLPfixed[v] ? GLP[v] : -1;
    }
    GLPvisit[v] = true;
    GLP[v] = 0;
    edge* e = Ge[v];
    while(e!=NULL)
    {
        int l = GLP_DFS(e->to);
        if(l == -1) return -1;
        GLP[v] = max(GLP[v], l+1);
        e = e->next;
    }
    GLPfixed[v] = true;
    return GLP[v];
}
int GLongestPath(void)
{
    int lmax = 0;
    for(int i=0;i<Gv;i++)
    {
        int l = GLP_DFS(i);
        if(l==-1)
        {
            return -1;
        }
        lmax = max(lmax, l);
    }
    return lmax;
}

int sid[MAXN][MAXN];
int a[MAXN][MAXN-1];

int main(void)
{
    int n;
    scanf("%d",&n);

    int s = 0;
    for(int i=0;i<n-1;i++)for(int j=i+1;j<n;j++)
    {
        sid[i][j] = s;
        sid[j][i] = s;
        s++;
    }

    for(int i=0;i<n;i++)for(int j=0;j<n-1;j++)
    {
        scanf("%d",&(a[i][j]));
        a[i][j]--;
    }

    Ginit(s);
    for(int i=0;i<n;i++)for(int j=0;j<n-2;j++)
    {
        Gadd(sid[i][a[i][j]], sid[i][a[i][j+1]]);
    }

    int ans = GLongestPath();
    if(ans == -1)
    {
        printf("-1\n");
        return 0;
    }
    
    printf("%d\n", ans+1);
    return 0;
}