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: Time Limit Exceeded)

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        new Magatro().Solve();
    }
}

class ST
{
    private int N=1<<18;
    private int[]Tree;
    public ST(int[]array)
    {
        Tree=new int[N*2];
        for(int i=0;i<N*2;i++)
        {
            Tree[i]=int.MaxValue;
        }
        for(int i=0;i<array.Length;i++)
        {
            Tree[N+i]=array[i];
        }
        for(int i=N-1;i>=1;i--)
        {
            Tree[i]=Math.Min(Tree[i*2],Tree[i*2+1]);
        }
    }
    public int Query(int a,int b,int k,int l,int r)
    {
        if(a<=l&&r<=b)
        {
            return Tree[k];
        }
        if(b<=l||r<=a)
        {
            return int.MaxValue;
        }
        int left=Query(a,b,k*2,l,(l+r)/2);
        int right=Query(a,b,k*2+1,(l+r)/2,r);
        return Math.Min(left,right);
    }
    public int Q(int a,int b)
    {
        return Query(a,b,1,0,N);
    }
}

class Magatro
{
    private int N;
    private int[]A;
    private void Scan()
    {
        N=int.Parse(Console.ReadLine());
        var l=Console.ReadLine().Split(' ');
        A=new int[N];
        for(int i=0;i<N;i++)
        {
            A[i]=int.Parse(l[i]);
        }
    }
    
    public void Solve()
    {
        Scan();
        ST st=new ST(A);
        long anser=0;
        for(int i=0;i<N;i++)
        {
            int left,right;
            int ng;
            //left
            left=i;
            ng=-1;
            while(left-ng>1)
            {
                int mid=(left+ng)/2;
                if(st.Q(mid,i+1)==A[i])
                {
                    left=mid;
                }
                else
                {
                    ng=mid;
                }
            }
            //right
            right=i;
            ng=N;
            while(ng-right>1)
            {
                int mid=(right+ng)/2;
                if(st.Q(i,mid+1)==A[i])
                {
                    right=mid;
                }
                else
                {
                    ng=mid;
                }
            }
            anser+=(long)(i-left+1)*(right-i+1)*A[i];
            
        }
        Console.WriteLine(anser);
    }
}