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 (3.4.3) (judge verdict: Time Limit Exceeded)

n=int(input())
ide_ele=n
num=2**(n-1).bit_length()
seg=[ide_ele]*2*num
segfunc=min

def init(init_val):
  for i in range(n):
    seg[i+num-1]=init_val[i]    
    for i in range(num-2,-1,-1) :
      seg[i]=segfunc(seg[2*i+1],seg[2*i+2]) 
    
def update(k,x):
  k+=num-1
  seg[k]=x
  while k+1:
    k=(k-1)//2
    seg[k]=segfunc(seg[k*2+1],seg[k*2+2])
    
def query(p,q):
  if q<=p:
    return ide_ele
  p+=num-1
  q+=num-2
  res=ide_ele
  while q-p>1:
    if p&1==0:
      res=segfunc(res,seg[p])
    if q&1==1:
      res=segfunc(res,seg[q])
      q-=1
    p=p//2
    q=(q-1)//2
  if p==q:
    res=segfunc(res,seg[p])
  else:
    res=segfunc(segfunc(res,seg[p]),seg[q])
  return res
init_val=[int(i) for i in input().split()]
init(init_val)
ans=0
for i in range(n):
  for j in range(i,n):
    ans+=query(i,j+1)
print(ans)