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>
#define REP(i,a,b) for(int i=(a);i<(b);i++)
#define RREP(i,a,b) for(int i=(a);i>=(b);i--)
#define pq priority_queue
#define P pair<int,int>
#define P2 pair<int,P>
#define P3 pair<int,P2>
typedef long long ll; typedef long double ld;
using namespace std;
const int INF=1e9, MOD=1e9+7, around[]={0,1,1,-1,-1,0,-1,1,0,0};
const int vx[]={1,0,-1,0}, vy[]={0,1,0,-1};
const int sqrtN = 512;
const int logN = 32;
const ll LINF=1e18;
const ld PI=abs(acos(-1));

int li[200010], li2[200010];

int main(){
	int n; cin >> n; int a[200010];
	REP(i, 0, n) cin >> a[i];
	
	stack<P> st;
	REP(i, 0, n){
		while(!st.empty() and st.top().second > a[i]){
			li2[st.top().first] = i - st.top().first;
			st.pop();
		}
		
		if(!st.empty()) li[i] = i - st.top().first;
		else li[i] = i + 1;
		st.push({i, a[i]});
	}
	
	while(!st.empty()){
		li2[st.top().first] = n - st.top().first;
		st.pop();
	}
	
	ll pos = 0;
	REP(i, 0, n) pos += a[i] * li[i] * li2[i];
	cout << pos << endl;
	return 0;
}