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: Wrong Answer)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define F first
#define S second
#define pii pair<int, int>
#define eb emplace_back
#define all(v) v.begin(), v.end()
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rep3(i, l, n) for (int i = l; i < (n); ++i)
#define sz(v) (int)v.size()
#define inf (int)(1e9+7)
#define abs(x) (x >= 0 ? x : -(x))
#define ceil(a, b) a / b + !!(a % b)
template<typename T1, typename T2> inline void chmin(T1 &a, T2 b) { if (a > b) a = b; }
template<typename T1, typename T2> inline void chmax(T1 &a, T2 b) { if (a < b) a = b; }
ll pow(ll a, int b) { return b ? pow(a * a, b / 2) * (b % 2 ? a : 1) : 1; }
template<typename T> T gcd(T a, T b) { if (b == 0) return a; return gcd(b, a % b); }


int main() {
    
    int n;
    cin >> n;
    
    vector<int> a(n), idx(n);
    rep(i, n) { cin >> a[i]; a[i]--; }
    
    rep(i, n) idx[a[i]] = i;
    
    set<int> s;
    ll ans = 0;
    rep(i, n) {
        int x = idx[i];
        s.insert(x);
        
        auto it = s.find(x);
        int r = n - 1, l = 0;
        if (it != s.begin()) {
            it--;
            l = *it;
            l++;
        }
        it = s.find(x);
        it++;
        if (it != s.end()) {
            r = *it;
            r--;
        }
        // cout << l << " " << r << '\n';
        ll c = (r - x + 1) * (x - l + 1);
        ans += (ll)(i + 1) * c;
        // cout << ans << '\n';
    }
    cout << ans << '\n';
}