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<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=200002;
int n,i,k,f[N],l[N],r[N],a[N],d[N];
ll ans;
bool cmp(int x,int y){
	return a[x]>a[y];
}
int p(int x){
	return f[x]==x?x:f[x]=p(f[x]);
}
int main(){
	scanf("%d",&n);
	for(i=1;i<=n;i++){
		scanf("%d",a+i);
		l[i]=r[i]=f[i]=d[i]=i;
	}
	sort(d+1,d+n+1,cmp);
	for(i=1;i<=n;i++){
		k=d[i];
		if(a[k-1]>a[k]){
			l[k]=l[p(k-1)];
			f[p(k-1)]=k;
		}
		if(a[k+1]>a[k]){
			r[k]=r[p(k+1)];
			f[p(k+1)]=k;
		}
		ans+=1ll*a[k]*(r[k]-k+1)*(k-l[k]+1);
	}
	printf("%lld\n",ans);
}