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

const N=parse(Int,readline())
const P=map(x->parse(Int,x),split(readline()))
const A=zeros(Int,N)
const B=zeros(Int,N)
const Ta=zeros(Int,17,N)
function init()
	B[1]=1
	for i=1:N
		A[P[i]]=i
		if i>1
			B[i]=B[i>>1]+1
		end
		Ta[1,i]=P[i]
	end
	for k=2:16
		L=1<<(k-2)
		for i=1:N-L+1
			Ta[k,i]=Ta[k-1,i]
			if i+L+L<=N+1&&Ta[k,i]<Ta[k-1,i+L]
				Ta[k,i]=Ta[k-1,i+L]
			end
		end
	end
end
function query(L,R)
	if L>=R
		return 0
	end
	b=B[R-L]
	X=max(Ta[b,L],Ta[b,R-(1<<(b-1))])
	X
end
init()
function main()
	ans=0
	for i=N-1:-1:1
		id=A[i]
		L1L=0
		L1R=id
		if query(1,id)<i
			L1R=0
		end
		while L1R-L1L>1
			L1M=div(L1R+L1L,2)
			if query(L1M,id)>i
				L1L=L1M
			else
				L1R=L1M
			end
		end
		L1=id-L1L
		L2L=0
		L2R=L1L
		while L2R-L2L>1
			L2M=div(L2R+L2L,2)
			if query(L2M,L1L)>i
				L2L=L2M
			else
				L2R=L2M
			end
		end
		L2=L1L-L2L
		R1L=id+1
		R1R=N+1
		if query(id,N+1)==i
			R1L=N+1
		end
		while R1R-R1L>1
			R1M=div(R1R+R1L,2)
			if query(id,R1M)>i
				R1R=R1M
			else
				R1L=R1M
			end
		end
		R1=R1L-id
		R2L=R1R
		R2R=N+1
		if query(R1R,N+1)<i
			R2L=N+1
		end
		while R2R-R2L>1
			R2M=div(R2R+R2L,2)
			if query(R1R,R2M)>i
				R2R=R2M
			else
				R2L=R2M
			end
		end
		R2=R2L-R1L
		ans+=i*(L1*R2+R1*L2)
	end
	println(ans)
end
main()