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;

template<class T> inline void read(T &x) {
    x = 0;
    char ch = getchar(), w = 0;
    while (!isdigit(ch)) w = (ch == '-'), ch = getchar();
    while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
    x = w ? -x : x;
    return;
}

long long n, a[2000005], stk[2000005], r[2000005], l[2000005];
long long ans, top;

inline void init() {
    read(n);
    for (int i = 1; i <= n; ++i)
        read(a[i]), r[i] = n + 1, l[i] = 0;
    return;
}

inline void solve() {
    for (int i = 1; i <= n; ++i) {
        while (top && a[stk[top]] > a[i])
            r[stk[top]] = i, top--;
        l[i] = stk[top];
        stk[++top] = i;
    }
    for (int i = 1; i <= n; ++i)
        ans += (r[i] - i) * (i - l[i]) * a[i];
    cout << ans << endl;
    return;
}

int main() {
    init();
    solve();
    return 0;
}