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 (Clang 3.8.0) (judge verdict: Time Limit Exceeded)

#include <string.h>
#include <string>
#include <vector>
#include <deque>
#include <list>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <iterator>
#include <functional>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cstdio>
using namespace std;
#define sz(a)  int((a).size())
#define all(a) a.begin(), a.end()
#define pb push_back
#define mp make_pair
#define CLR(a) memset((a), 0, sizeof(a))
#define INF (1 << 31) - 1
const int dh[8] = {-1, 1, 0, 0,1,1,-1,-1};
const int dw[8] = {0, 0, 1, -1,1,-1,1,-1};
typedef long long ll;
typedef pair<int, int> p;
typedef vector <int> VI;
typedef vector <string> VS;


int main(){
	
	int n;
	cin >> n;
	VI a(n+1);

	for(int i = 1; i <= n; i++){
		int num;
		cin >> num;
		a[num] = i;
	}
	
	ll ans = 0;
	vector <int> his;
	his.pb(0);
	his.pb(n+1);

	for(int i = 1; i <= n; i++){
		his.pb(a[i]);
		sort( all(his) );
		vector<int>::iterator it = lower_bound( all(his), a[i] );
		int h = a[i] - *(it - 1);
		int w = *(it + 1) - a[i];	
						
		ans += h * w * i;
	}

	cout << ans << endl;

	return 0;	
}