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

def nibutan(arr,max,min,key)
  if max < min
    return min
  else
    mid = min+(max-min)/2
    if arr[mid] > key
      nibutan(arr,mid-1,min,key)
    elsif arr[mid] < key
      nibutan(arr,max,mid+1,key)
    else
      return mid
    end
  end
end
n = gets.to_i
a = gets.chomp.split(" ").map{|i|i.to_i-1}
addr = Array.new(n)
for i in 0..n-1
  addr[a[i]] = i
end
stack = [addr[0]]
ans = (addr[0]+1)*(n-addr[0])
for i in 1..n-1
  temp = nibutan(stack,i-1,0,addr[i])
  stack.insert(temp,addr[i])
  if temp != 0 && temp != i
    ans += (stack[temp]-stack[temp-1])*(stack[temp+1]-stack[temp])*(i+1)
  elsif temp == 0
    ans += (stack[1]-stack[0])*(i+1)*(stack[0]+1)
  else
    ans += (stack[-1]-stack[-2])*(i+1)*(n-stack[-1])
  end
end
p ans