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 PyPy3 (2.4.0) (judge verdict: Accepted)

from bisect import*
class BTreeNode:
    def __init__(self):self.key,self.child=[],[]
class BTree:
    def __init__(self):self.root=BTreeNode()
    def search_higher(self,key):
        ptr=self.root
        ret=None
        while ptr.child:
            i=bisect(ptr.key,key)
            if i!=len(ptr.key):ret=ptr.key[i]
            ptr=ptr.child[i]
        i=bisect(ptr.key,key)
        if i!=len(ptr.key):ret=ptr.key[i]
        return ret
    def search_lower(self,key):
        ptr=self.root
        ret=None
        while ptr.child:
            i=bisect_left(ptr.key,key)
            if i:ret=ptr.key[i-1]
            ptr=ptr.child[i]
        i=bisect_left(ptr.key,key)
        if i:ret=ptr.key[i-1]
        return ret
    def insert(self,key):
        def insert_rec(ptr,key):
            b_size=512
            if not ptr.child:
                insort(ptr.key,key)
                if len(ptr.key)==b_size*2-1:
                    ret=BTreeNode()
                    ret.key=ptr.key[:b_size]
                    ptr.key=ptr.key[b_size:]
                    return ret
            else:
                i=bisect(ptr.key,key)
                tmp=insert_rec(ptr.child[i],key)
                if tmp:
                    ptr.key.insert(i,tmp.key.pop())
                    ptr.child.insert(i,tmp)
                    if len(ptr.child)==b_size*2:
                        ret=BTreeNode()
                        ret.child=ptr.child[:b_size]
                        ptr.child=ptr.child[b_size:]
                        ret.key=ptr.key[:b_size]
                        ptr.key=ptr.key[b_size:]
                        return ret
                return None
        tmp=insert_rec(self.root,key)
        if tmp:
            root=BTreeNode()
            root.key=[tmp.key.pop()]
            root.child=[tmp,self.root]
            self.root=root
def main():
    n,*a=map(int,open(0).read().split())
    l=[0]*n
    for i,v in enumerate(a,1):l[v-1]=i
    t=BTree()
    t.insert(0)
    t.insert(n+1)
    c=0
    for i,v in enumerate(l,1):
        c+=(t.search_higher(v)-v)*(v-t.search_lower(v))*i
        t.insert(v)
    print(c)
main()