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: Time Limit Exceeded)

#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <sstream>
#include <algorithm>
#include <deque>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <list>
#include <cstdio>
#include <iostream>
#include <cmath>
#include <climits>
#include <bitset>
#include <functional>
#include <numeric>
#include <ctime>
#include <cassert>
#include <cstring>
#include <fstream>

#define FOR(i, a, b) for(int (i)=(a); (i)<(b); (i)++)
#define RFOR(i, a, b) for(int (i)=(a);(i)>=(b);(i)--)

using namespace std;

int main() {
	int n;
	cin >> n;
	vector<int> a(n);
	vector<int> position(n + 1);
	FOR(i, 0, n) {
		scanf("%d", &a[i]);
		position[a[i]] = i;
	}
	set<int> border;
	long long sumx = 0;
	FOR(i, 1, n + 1) {
		int nowpos = position[i];

		// upper_bound(border.begin(), border.end(), nowpos)じゃだめらしい(時間が)
		auto pos = upper_bound(border.begin(), border.end(), nowpos);// border.upper_bound(nowpos);

		int ub, lb;
		if (border.size() == 0) {
			ub = n, lb = -1;
		}

		else if (pos == border.end()) {
			ub = n;
			lb = *border.rbegin();
		}
		else {
			ub = *pos;
			if (pos == border.begin())
				lb = -1;
			else
				lb = *(--pos);
		}

		long long left = nowpos - lb - 1;
		long long right = ub - nowpos - 1;
		if (left < right)
			swap(left, right);

		long long toadd = (long long)i*(right + 1)*(left + 1);
		sumx += toadd;
		border.insert(nowpos);
	}
	cout << sumx << endl;


	return 0;
}