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 <iostream>
#include <algorithm>
#include <string>
#include <queue>
#include <vector>
#include <set>
#include <bitset>
#include <cmath>
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define ROF(i,a,b) for(int i=b-1;i>=a;i--)
#define FI first
#define SE second
#define MA(i,j) make_pair(i,j)
#define PA pair<int,int>
#define PB push_back
#define PQ priority_queue<int>
#define PGQ priority_queue<int,vector<int>,greater<int> >
#define VE vector<int>
#define VP vector<PA>
#define YES(i) cout<<(i?"YES":"NO")<<endl
#define Yes(i) cout<<(i?"Yes":"No")<<endl
#define MOD 1000000007
#define INF 1000000007
#define PI 3.141592653589793238462643383279
using namespace std;
//
const int MAX_N=2000000;
//
long long N,DAT[2*MAX_N-1];
//前処理
void init(int N_){
  N=1;
  while(N<N_){
    N*=2;
  }
  FOR(i,0,2*N-1){
    DAT[i]=1e15;
  }
}
//初期化
void update(int K,int A){
  K+=N-1;
  DAT[K]=A;
  while(K>0){
    K=(K-1)/2;
    DAT[K]=min(DAT[K*2+1],DAT[K*2+2]);
  }
}
//[A,B)の最小値を返す
long long query(int A,int B,int K,int L,int R){
  if(R<=A||B<=L){
    return 1e15;
  }else if(A<=L&&R<=B){
    return DAT[K];
  }else{
    long long VL=query(A,B,K*2+1,L,(L+R)/2);
    long long VR=query(A,B,K*2+2,(L+R)/2,R);
    return min(VL,VR);
  }
}
int main(){
  int M,P;
  cin>>M;
  N=M;
  init(N);
  FOR(i,0,M){
    cin>>P;
    update(i,P);
  }
  long long sum=0;
  //i個の連続した部分列の最小値を足していく
  FOR(i,1,M+1){
    FOR(j,0,M-i+1){
      //a[j]~a[j+i]の最小値
      sum+=query(j,j+i,0,0,N);
    }
  }
  cout<<sum<<endl;
  return 0;
}