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: Accepted)

# 入力
import sys
stdin = sys.stdin

def li(): return [int(x) for x in stdin.readline().split()]
def li_(): return [int(x)-1 for x in stdin.readline().split()]
def lf(): return [float(x) for x in stdin.readline().split()]
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(ns())
def nf(): return float(ns())

n = ni()
a = li()

# 各数のindexを格納
dic = {}
for i, ai in enumerate(a):
    dic[ai] = i
    
# 各indexに対して、左端のindexをleft, 右端のindexをrightに格納する
left = list(range(n+2))
right = list(range(n+2))

ans = 0
for i in range(n,0,-1):
    idx = dic[i]
    ans += i * (right[idx] - idx + 1) * (idx - left[idx] + 1)
    right[left[idx] - 1] = right[idx]
    left[right[idx] + 1] = left[idx]

print(ans)