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 <cstring>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cassert>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <functional>
#include <iostream>
#include <map>
#include <set>
#include <cassert>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
typedef pair<int,P> P1;
typedef pair<P,P> P2;
#define pu push
#define pb push_back
#define mp make_pair
#define eps 1e-7
#define INF 1000000000
#define fi first
#define sc second
#define rep(i,x) for(int i=0;i<x;i++)
#define SORT(x) sort(x.begin(),x.end())
#define ERASE(x) x.erase(unique(x.begin(),x.end()),x.end())
#define POSL(x,v) (lower_bound(x.begin(),x.end(),v)-x.begin())
#define POSU(x,v) (upper_bound(x.begin(),x.end(),v)-x.begin())
int a[200005],pos[200005],n;
ll ret;
int main()
{
	cin >> n;
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
		pos[a[i]] = i;
	}
	set<P>S;
	S.insert(mp(1,n));
	for(int i=1;i<=n;i++){
		set<P>::iterator it = S.upper_bound(mp(pos[i],INF));
		it--;
		int L = (*it).fi, R = (*it).sc; S.erase(it);
		
		ll x = R - L+ 1; x = x*(x+1)/2LL;
		ll y = 0;
		if(L < pos[i]){
			ll D = pos[i] - L;
			y += D*(D+1)/2LL;
			S.insert(mp(L,pos[i]-1));
		}
		if(R > pos[i]){
			ll D = R - pos[i];
			y += D*(D+1)/2LL;
			S.insert(mp(pos[i]+1,R));
		}
		ret += (x-y) * i;
	}
	cout << ret << endl;
}