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# (Mono 4.6.2.0) (judge verdict: Accepted)

using System;
using System.Collections.Generic;
class Solve{
    int N;
    int[] a;
    public Solve(){}
    public static int Main(){
        new Solve().Calc();
        return 0;
    }
    void Calc(){
        getinput();
        int[] sort = new int[N];
        int[] linka = new int[N];
        int[] linkb = new int[N];
        long count = 0;
        for(int i=0;i < N;i++){
            sort[i] = i;
            linka[i] = i+1;
            linkb[i] = i-1;
        }
        Array.Sort(sort,(c,b) => a[b] - a[c]);
        for(int i=0;i<N;i++){
            int min = linkb[sort[i]];
            int max = linka[sort[i]];
            if(min != -1){
                linka[min] = max;
            }
            if(max != N){
                linkb[max] = min;
            }
            count += (long)(max-sort[i])*(long)(sort[i]-min)*(long)a[sort[i]];
        }
        Console.WriteLine(count);
    }
    void getinput(){
        N = int.Parse(Console.ReadLine());
        string[] str = Console.ReadLine().Split(' ');
        a = new int[N];
        for(int i=0;i<N;i++){
            a[i] = int.Parse(str[i]);
        }
    }    
}