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)

/*
 * src.cpp
 *
 *  Created on: 2016/10/01
 *      Author: joi
 */

#include <bits/stdc++.h>

using namespace std;

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,a) FOR(i,0,a)

const int MAX_N=2e5;

typedef long long ll;
int N;
int A[MAX_N];
ll dp[MAX_N];

int main(){
	scanf("%d",&N);
	REP(i,N){
		scanf("%d",&A[i]);
	}
	ll res=A[0];
	int mi=A[0];
	dp[0]=A[0];
	FOR(i,1,N){
		ll d=0;
		res+=A[i];
		d=A[i];
		if (A[i]<mi){
			mi=A[i];
			res+=mi*i;
			d+=mi*i;
		}else{
			int j=i-1;
			while (A[j]>A[i]){
				res+=A[i];
				d+=A[i];
				j--;
			}
			res+=dp[j];
			d+=dp[j];
		}
		dp[i]=d;
	}
	printf("%lld\n",res);
	return 0;
}