[ABC140E] 全体子段次大值之和 (Second Sum)
Score: points
Problem Statement
Given is a permutation of .
For a pair , let be the second largest value among .
Find $\displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}$.
Constraints
-
-
-
-
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
, and , so the sum is .
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