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 <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define add push_back
#define f first
#define s second
#define pw(x) (1ll << (x))
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()
const ll INF = (ll)1e9 + 2019;

const int N = 2e5 + 10;
int arr[N], t[N * 4], nl[N], nr[N];

int query(int v, int l, int r, int a, int b) {
	if (a > r || l > b) {
		return -INF;
	}
	if (a <= l && r <= b) {
		return t[v];
	}
	int m = (l + r) / 2;
	return max(query(v * 2, l, m, a, b), query(v * 2 + 1, m + 1, r, a, b));
}

void update(int v, int l, int r, int p, int x) {
	if (l == r) {
		t[v] = x;
		return;
	}
	int m = (l + r) / 2;
	if (p <= m) {
		update(v * 2, l, m, p, x);
	} else {
		update(v * 2 + 1, m + 1, r, p, x);
	}
	t[v] = max(t[v * 2], t[v * 2 + 1]);
}

void mane() {
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> arr[i];
	}
	memset(t, -1, sizeof(t));
	for (int i = 0; i < n; i++) {
		nl[i] = query(1, 0, n, 0, arr[i] - 1);
		update(1, 0, n, arr[i], i);
	}
	for (int i = 0; i < N * 4; i++) {
		t[i] = -n;
	}
	for (int i = n - 1; i >= 0; i--) {
		nr[i] = -query(1, 0, n, 0, arr[i] - 1);
		update(1, 0, n, arr[i], -i);
	}
	ll ans = 0;
	for (int i = 0; i < n; i++) {
		ans += (ll)arr[i] * (i - nl[i]) * (nr[i] - i);
		//cerr << i << " " << nl[i] << " " << nr[i] << endl;
	}
	cout << ans;
}

int32_t main() {
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	mane();
#ifdef flaax
	cout << endl; cerr << endl << "\t" << fixed << setprecision(12) << (ld)clock() / CLOCKS_PER_SEC << " sec" << endl;
#endif
}