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 Python (2.7.6) (judge verdict: Accepted)

class UnionFind:
    def __init__(self,size):
        self.parent=range(size)
        self.tree_num=size
        self.tree_w=[1]*size
        self.rank=[0]*size

    def findset(self,x):
        if self.parent[x]==x:
            return x
        else:
            self.parent[x]=self.findset(self.parent[x])
            return self.parent[x]

    def unite(self,x,y):
        x=self.findset(x)
        y=self.findset(y)
        if x==y:
            return
        if self.rank[x]<self.rank[y]:
            self.parent[x]=y
            self.tree_num-=1
            self.tree_w[y]+=self.tree_w[x]
        else:
            self.parent[y]=x
            self.tree_num-=1
            self.tree_w[x]+=self.tree_w[y]
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def tree_weight(self,x):
        return self.tree_w[self.findset(x)]

n=int(raw_input())
a=map(int,raw_input().split())
p=[0]*(n+1)
for i in xrange(n):
    p[a[i]]=i

uf=UnionFind(n+1)
ans=0
for j in xrange(n,0,-1):
    i=p[j]
    tmp=1
    if i>=1 and a[i]<a[i-1]:
        tmp*=uf.tree_weight(a[i-1])+1
        uf.unite(a[i],a[i-1])
    if i<n-1 and a[i]<a[i+1]:
        tmp*=uf.tree_weight(a[i+1])+1
        uf.unite(a[i],a[i+1])
    ans+=j*tmp
print(ans)