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: Runtime Error)

maxcost = 10**10
n = int(input())
num = [ int(v) for v in input().split() ]
pos = sorted([ (v, i) for i, v in enumerate(num,1) ])
pos = [ i[1] for i in pos ]
ln = len(bin(n-1))-1
ln2 = 2**(ln-1)
segtree = [ maxcost for i in range(2**ln-1) ]
#最小値用

def update_tomin(tree, p, q=1):
    p += 2**(ln-1)-2
    while p >= 0:
        tree[p] = min(tree[p], q)
        p = (p-1)//2

def getmin(tree,a,b,k=0,l=0,r=ln2):
    if r <= a or b <= l:
        return maxcost
    elif a <= l and r <= b:
        return tree[k]
    else:
        return min( getmin(tree,a,b,2*k+1,l,(l+r)//2), getmin(tree,a,b,2*k+2,(l+r)//2,r) )

for i, v in enumerate(num):
    update_tomin(segtree,i+1,v)

def divconq(a, b):
    if a == b:
        return num[a-1]
    else:
        m = getmin(segtree,a-1,b)
        k = pos[m-1]
        s = m * (b-k+1) * (k-a+1)
        if k == a:
            return s + divconq(a+1, b)
        elif k == b:
            return s + divconq(a, b-1)
        else:
            return s + divconq(a, k-1) + divconq(k+1, b)

print(divconq(1,n))