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: Wrong Answer)

#include <bits/stdc++.h>
using namespace std;

#define fi first
#define se second
#define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define rep(i,n) repl(i,0,n)
#define each(itr,v) for(auto itr:v)
#define pb(s) push_back(s)
#define mp(a,b) make_pair(a,b)
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout<<#x"="<<x<<endl
#define maxch(x,y) x=max(x,y)
#define minch(x,y) x=min(x,y)
#define uni(x) x.erase(unique(all(x)),x.end())
#define exist(x,y) (find(all(x),y)!=x.end())
#define bcnt(x) bitset<32>(x).count()

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;
typedef pair<P, int> PPI;
typedef pair<ll, ll> PL;
typedef pair<P, ll> PPL;

#define INF INT_MAX/3

#define MAX_N 1000

int n;
ll h[111111];
int L[111111],R[111111];

stack<int> st;

int main(){
	cin.sync_with_stdio(false);
	cin>>n;
	rep(i,n)cin>>h[i];
	rep(i,n){
		while(!st.empty()&&h[st.top()]>=h[i])st.pop();
		L[i]=st.empty()?0:(st.top()+1);
		st.push(i);
	}
	stack<int>().swap(st);
	for(int i=n-1;i>=0;i--){
		while(!st.empty()&&h[st.top()]>=h[i])st.pop();
		R[i]=st.empty()?n:(st.top());
		st.push(i);
	}
	ll res=0;
	rep(i,n){
		res+=(h[i])*(R[i]-i)*(i-L[i]+1);
	}
	cout<<res<<endl;
	return 0;
}