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<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<climits>
#define int long long
using namespace std;
inline int read(){
	int f=1,ans=0;char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
	while(c>='0'&&c<='9'){ans=ans*10+c-'0';c=getchar();}
	return f*ans;
}
const int MAXN=200001;
int st[MAXN][21],n,a[MAXN];
int Query(int l,int r){
	int k=log2(r-l+1);
	return min(st[l][k],st[r-(1<<k)+1][k]);
}
int Ql(int x){
	int l=1,r=x-1,minn=INT_MAX;
	while(l<=r){
		int mid=l+r>>1;
		if(Query(mid,x-1)>a[x]) r=mid-1,minn=min(minn,mid);
		else l=mid+1;
	}return minn;
}
int Qr(int x){
	int l=x+1,r=n,maxn=	INT_MIN;
	while(l<=r){
		int mid=l+r>>1;
		if(Query(x+1,mid)>=a[x]) l=mid+1,maxn=max(maxn,mid);
		else r=mid-1; 
	}return maxn;
}int ans;
signed main(){
//	freopen("6.in","r",stdin);
	n=read();
	for(int i=1;i<=n;i++) a[i]=st[i][0]=read();
	for(int j=1;j<=log2(n);j++)
		for(int i=1;i+(1<<j)-1<=n;i++) st[i][j]=min(st[i][j-1],st[i+(1<<(j-1))][j-1]);
	for(int i=1;i<=n;i++){
		int l=Ql(i),r=Qr(i);
		if(l==INT_MAX) l=i;
		if(r==INT_MIN) r=i;
		int lena=i-l,lenb=r-i;
		ans+=(lena+lenb+1+lena*lenb)*a[i];
	}printf("%lld\n",ans);
}