Problem:
Score : 400 points

Problem Statement

One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.

Find the following:

Constraints

1 ≦ N ≦ 200,000

(a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the answer.

Note that the answer may not fit into a 32-bit integer.

Sample Input 1

3
2 1 3

Sample Output 1

9

Sample Input 2

4
1 3 2 4

Sample Output 2

19

Sample Input 3

8
5 4 8 1 2 6 7 3

Sample Output 3

85

Solution in C++14 (GCC 5.4.1) (judge verdict: Accepted)

#include <bits/stdc++.h>
using namespace std ;
template < class R > inline void Readin( R &K ) {bool F=K=0;char C=getchar();while(C<'0'||C>'9')
{if(C=='-')F=1;C=getchar();}while(C<='9'&&C>='0')K=(K<<1)+(K<<3)+C-'0',C=getchar();if(F)K=-K;}
template < class R > inline bool Checkmax( R &A , R B ) { return A < B ? A = B , 1 : 0 ; }
template < class R > inline bool Checkmin( R &A , R B ) { return A > B ? A = B , 1 : 0 ; }
const int MaxN = 200000 + 10 ;
int N , P[MaxN] , Np[MaxN] ;
int Siz[MaxN] , Find[MaxN] ;
long long Ans ;
int F( int Nod ) {
	return Find[Nod] ? ( Find[Nod] == Nod ? Nod : Find[Nod] = F( Find[Nod] ) ) : 0 ;
}
inline void Merge( int A , int B ) {
	A = F(A) ;
	B = F(B) ;
	if( B ) {
		Siz[A] += Siz[B] ;
		Find[B] = A ;
	}
}
int main() {
	Readin( N ) ;
	for(register int i = 0 ; ++i <= N ; ) {
		Readin( P[i] ) ;
		Np[P[i]] = i ;
	}
	for(register int i = N ; i ; --i ) {
		Ans += 1ll * ( Siz[F(Np[i]-1)] + 1 ) * ( Siz[F(Np[i]+1)] + 1 ) * i ;
		Find[Np[i]] = Np[i] ;
		Siz[Np[i]] = 1 ;
		Merge( Np[i] , Np[i] - 1 ) ;
		Merge( Np[i] , Np[i] + 1 ) ;
	}
	return not printf( "%lld\n" , Ans ) ;
}