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 PyPy3 (7.3.0) (judge verdict: Accepted)

import sys
input = sys.stdin.readline
N = int(input())
P = list(map(int,input().split()))

'''
import random
N = 100000
P = list(range(1,N+1))
#random.shuffle(P)
'''

class SegmentTree:
    def __init__(self,data,op,default):
        N = len(data)
        self.N = N
        self.op = op
        self.default = default
        self.l = 2**((N-1).bit_length())
        self.data = [default]*self.l + data + [default]*(self.l-N)
        for i in range(self.l-1,0,-1):
            self.data[i] = op(self.data[2*i], self.data[2*i+1])

    def get_data(self):
        return self.data[self.l:self.l + self.N]

    def set(self,i,val):
        i += self.l
        self.data[i] = val
        i = i//2
        while i > 0:
            self.data[i] = self.op(self.data[2*i], self.data[2*i+1])
            i = i//2

    def get(self,i,j):
        i += self.l
        j += self.l
        s = self.default 
        while j-i > 0:
            if i & 1:
                s = self.op(s,self.data[i])
                i += 1
            if j & 1:
                s = self.op(s,self.data[j-1])
                j -= 1
            i = i//2
            j = j//2
        return s

P2 = [[[p,i],[0,0]] for i,p in enumerate(P)]

max2 = lambda x,y : sorted(x+y,reverse=True)[:2]

seg = SegmentTree(P2,max2,[[0,0],[0,0]])

cand = [[0,N]]

ans = 0
visited = set([])
while cand:
    #print(cand)
    temp = []
    for l,r in cand:
        if r-l < 2:
            continue
        if (l,r) in visited:
            continue
        visited.add((l,r))
        (m1,i1), (m2,i2) = seg.get(l,r)
        #print(P[l:r],m1,m2)
        i1,i2 = (i1,i2) if i1 < i2 else (i2,i1)
        ans += m2 * (i1-l+1) * (r-i2)
        temp.append([l,i2])
        temp.append([i1+1,r])
    cand = temp

print(ans)