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;
using ll = long long;

template <typename T>
class SparseTable {
	int n;
	vector<vector<T>> t;
	T merge(const T& l, const T& r) {
		return min(l, r);
	}
public:
	SparseTable(const vector<T>& b) {
		n = b.size();
		t.push_back(b);
		for (int i = 2, j = 1; i <= n; i <<= 1, j++) {
			t.push_back(vector<T>());
			for (int k = 0; k + i <= n; k++) {
				t[j].push_back(merge(t[j - 1][k], t[j - 1][k + i / 2]));
			}
		}
	}
	T find(int l, int r) {
		r++;
		assert(0 <= l && l < r && r <= n);
		unsigned int w = r - l;
		int i = 31 - __builtin_clz(w);
		return merge(t[i][l], t[i][r - (1 << i)]);
	}
	T operator[](int id) {
		return t[0][id];
	}
};

int main()
{
	ios::sync_with_stdio(false), cin.tie(0);
	int N;
	cin >> N;
	vector<int> a(N);
	for (int i = 0; i < N; i++) {
		cin >> a[i];
	}
	ll res = 0;
	SparseTable<int> st(a);
	for (int i = 0; i < N; i++) {
		ll l = 0, r = 0;
		{
			int lb = -1, ub = i;
			while (ub - lb > 1) {
				int m = (lb + ub) / 2;
				if (st.find(m, i) == a[i]) {
					ub = m;
				}
				else {
					lb = m;
				}
			}
			l = ub;
		}
		{
			int lb = i, ub = N;
			while (ub - lb > 1) {
				int m = (lb + ub) / 2;
				if (st.find(i, m) == a[i]) {
					lb = m;
				}
				else {
					ub = m;
				}
			}
			r = lb;
		}
		res += (i - l + 1) * (r - i + 1) * a[i];
	}
	cout << res << endl;
	return 0;
}