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 (2.4.0) (judge verdict: Wrong Answer)

class Bit:
  def __init__(self,n):
    self.bl = n.bit_length()
    self.size = n
    self.tree = [0]*(n+1)
 
  def sum(self,i):
    s = 0
    while i > 0:
      s += self.tree[i]
      i -= i & -i
    return s

  def add(self,i,x):
    while i <= self.size:
      self.tree[i] += x
      i += i & -i

  #二分探索、x[未満or以下]のインデックス+1を返します
  def bs(self,x,side="l"):
    k = 1<<(self.bl-1)
    i = 0
    sm = 0
    flg = int(side!="l")
    while k:
      while i+k > self.size:
        k //= 2
      if sm+self.tree[i+k] < x+flg:
        sm += self.tree[i+k]
        i += k
      k //= 2
    return i+1

n = int(input())
a = list(map(int,input().split()))
da = {a[i]:i+1 for i in range(n)}
ans = 0
bit = Bit(n)
for i in range(n,0,-1):
  idx = da[i]
  x = bit.sum(idx)
  l2 = bit.bs(x-1,"l")
  l1 = bit.bs(x,"l")
  r1 = bit.bs(x+1,"l")
  r2 = bit.bs(x+2,"l")
  if i == n:
    bit.add(idx,1)
    continue
  if l1 == 1:
    l2 = 0
  if r1 == n+1:
    r2 = n+2
  if x == 0:
    ans += idx*(r2-r1)*i
  elif r1 == n+1:
    ans += (n-idx+1)*(l1-l2)*i
  else:
    if r1 < r2:
      ans += (r2-r1)*(idx-l1)*i
    if l2 < l1:
      ans += (l1-l2)*(r1-idx)*i
  bit.add(idx,1)
print(ans)