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 (GCC 5.4.1) (judge verdict: Runtime Error)

#include<stdio.h>
int n,B[100010]={0};
void badd(int i,int a){for(;i<=n;i+=i&-i)B[i]+=a;}
int  bsum(int i){
  int s=0;
  for(;i;i-=i&-i)s+=B[i];
  return s;
}
int L(int l,int r){//printf("L:%d %d\n",l,r);
  if(l==r)return l;
  int m=(l+r)/2;//printf("::m%d r%d m%d\n",m,bsum(r),bsum(m));
  if(bsum(r)-bsum(m)==0)return L(l,m);
  return L(m+1,r);
}
int R(int l,int r){//printf("R:%d %d\n",l,r);
  if(l+1==r)return l+1;
  int m=(l+r)/2;//printf("::m%d l%d m%d\n",m,bsum(l),bsum(m));
  if(bsum(m)==bsum(l))return R(m,r);
  return R(l,m);
}
int main(){
  int i,a,d[200010];
  long long s=0,r,l;
  scanf("%d",&n);
  for(i=0;i<n;i++){
    scanf("%d",&a);
    d[a-1]=i+2;
  }
  n+=2;
  badd(1,1);
  badd(n,1);
  //for(i=0;i<n;i++)printf("%d ",d[i]);printf("\n");
  //for(i=1;i<=n;i++)printf("%d ",bsum(i));printf("\n");
  for(i=0;i<n-2;i++){
    l=d[i]-L(1,d[i]-1);
    r=R(d[i],n)-d[i];//printf("%d %lld %d %lld\n",i+1,l,d[i],r);
    s+=l*r*(i+1);
    badd(d[i],1);
    //for(a=0;a<n;a++)printf("%d ",bsum(a+1));printf("\n");
    //printf("s%lld\n",s);
  }
  printf("%lld\n",s);
  return 0;
}