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 <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <queue>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;

static const double EPS = 1e-8;
static const double PI = 4.0 * atan(1.0);
static const double PI2 = 8.0 * atan(1.0);

#define REP(i,n)	for(int i=0;i<(int)n;++i)
#define ALL(c)		(c).begin(),(c).end()
#define CLEAR(v)	memset(v,0,sizeof(v))
#define MP(a,b)		make_pair((a),(b))
#define ABS(a)		((a)>0?(a):-(a))
#define FOR(i,s,n)	for(int i=s;i<(int)n;++i)

int n;
int a[200000];

int m;
int seg[600000];

void update(int i, int v) {
	i += m - 1;
	seg[i] = v;
	while (i > 0) {
		i = (i - 1) / 2;
		seg[i] = min(seg[i * 2 + 1], seg[i * 2 + 2]);
	}
}

int segq(int a, int b, int i, int l, int r) {
	if (r <= a || b <= l) return m;
	if (a <= l && r <= b) return seg[i];
	return min(segq(a, b, i * 2 + 1, l, (l + r) / 2), segq(a, b, i * 2 + 2, (l + r) / 2, r));
}

int segq(int a, int b) {
	return segq(a, b, 0, 0, m);
}

ll b[200002];

int main(int argc, char **argv) {
	cin >> n;
	REP(i, n) cin >> a[i];

	m = 1;
	while (m < n) m *= 2;
	REP(i, 2 * m - 1) seg[i] = n + 1;
	REP(i, n) update(i, a[i]);

	ll res = 0;
	REP(i, n) {
		ll t = a[i];
		if (segq(0, i) >= a[i]) {
			t *= i + 1;
		}
		else {
			int l = 0, r = i;
			while (l + 1 < r) {
				int m = (l + r) / 2;
				if (segq(m, r) < a[i]) l = m;
				else r = m;
			}
			t *= i - l;
		}
		if (segq(i + 1, n) >= a[i]) {
			t *= n - i;
		}
		else {
			int l = i + 1, r = n;
			while (l + 1 < r) {
				int m = (l + r) / 2;
				if (segq(l, m) < a[i]) r = m;
				else l = m;
			}
			t *= l - i;
		}
		res += t;
	}
	cout << res << endl;
	return 0;
}