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)

def bin_search(queue, num):
    if len(queue) == 0:
        return 0
    l = 0
    r = len(queue)
    while r-l > 1:
        m = (l+r) // 2
        if queue[m] < num:
            l = m
        else:
            r = m
            
    if l == 0 and queue[0] > num:
        r = 0
    return r


n = int(input())
a = list(map(int, input().split()))

for i in range(n):
    a[i] -= 1

loc = [-1 for i in range(n)]
for i in range(n):
    loc[a[i]] = i

l = [-1 for i in range(n)]
r = [-1 for i in range(n)]

q = []

for i in range(n):
    ind = bin_search(q, a[i])
    for j in range(ind, len(q)):
        r[q[j]] = i
    if ind ==len(q):
        q.append(a[i])
    else:
        q[ind] = a[i]
    q = q[:ind+1]
    if ind==0:
        l[a[i]] = 0
    else:
        l[a[i]] = loc[q[ind-1]]+1

for i in range(len(q)):
    r[q[i]] = n
    
ans = 0    
for i in range(n):
    a = (i+1) * (loc[i]-l[i]+1) * (r[i]-loc[i])
    ans += a

print(ans)