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)

/*
    Solution solved by Maksat Sakenuly
*/
#include <bits/stdc++.h>

#define F first
#define S second
#define pb push_back
#define eb emplace_back
#define sqr(x) ((x)*(x))
#define sz(x) int(x.size())
#define tos(str) string(#str)
#define gcd(x, y) __gcd(x, y)
#define all(x) x.begin(), x.end()
#define max3(a, b, c) max(a, max(b, c))
#define min3(a, b, c) min(a, min(b, c))
#define count1 __builtin_popcountl
#define tie cin.tie(0);cout.tie(0)
#define ios ios_base::sync_with_stdio(false)
#define debug(x) cout << (#x) << " is " << (x) << endl
#define m ((l + r)/ 2)

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> pll;
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
typedef vector<int> vi;
typedef vector <ll> vll;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<vector<int> > vvi;

const int oo = 0x3f3f3f3f;
const ll N = 2e5 + 123;
const ll MOD = 1e9 + 7;
const ll INF = 2e9 + 7;
const double pi = acos(-1);

int a[N], l[N], r[N];

int main() {
    ios; tie;

    int n;
    cin >> n;

    stack <int> s1, s2;
    for(int i = 1; i <= n; i++) {
        cin >> a[i];
        while(!s1.empty() && a[s1.top()] >= a[i]) s1.pop();
        if(s1.empty()) l[i] = 0;
        else l[i] = s1.top();
        s1.push(i);
    }
    for(int i = n; i >= 1; i--) {
        while(!s2.empty() && a[s2.top()] >= a[i]) s2.pop();
        if(s2.empty()) r[i] = n + 1;
        else r[i] = s2.top();
        s2.push(i);
    }

    ll ans = 0;
    for(int i = 1; i <= n; i++)
        ans += 1ll*(r[i]-i)*(i-l[i])*a[i];

    cout << ans;
    return 0;
}