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)

class SegTreeMin
    attr_reader :dat
    def initialize(n_input, top=Float::INFINITY)
        @n_input = n_input
        @n = 1 << @n_input.to_s(2).length
        @top = top
        @dat = Array.new(2 * @n - 1, @top)
    end

    def update(k, a)
        k += @n - 1
        @dat[k] = a
        while k > 0 do
            k = (k - 1) / 2
            #dat[k] = [dat[2*k+1], dat[2+k+2]].min
            @dat[k] = @dat[2*k+1]
            @dat[k] = @dat[2*k+2] if @dat[k] > @dat[2*k+2]
        end
    end

    # include a and b
    def min_between(a, b)
        query(a, b + 1, 0, 0, @n)
    end

    def query(a, b, k, l, r)
        return @top if r <= a || b <= l
        return @dat[k] if a <= l && r <= b
        vl = query(a, b, k * 2 + 1, l, (l + r) / 2)
        vr = query(a, b, k * 2 + 2, (l + r) / 2, r)
        #return [vl, vr].min
        return vl < vr ? vl : vr
    end
end

#t = Time.now
#N = 200000
#as = (1..N).to_a
N = gets.to_i
as = gets.split.map(&:to_i)
st = SegTreeMin.new(N)
rev = Array.new(N+1)
N.times do |i|
    st.update(i, as[i])
    rev[as[i]] = i
end

ans = 0
ls = [0]
rs = [N-1]
while ls.length > 0 do
    l = ls.pop
    r = rs.pop
    loop do
        if l == r
            ans += as[l]
            break
        end
        min = st.min_between(l, r)
        min_i = rev[min]
        if l == min_i
            ans += (r - min_i + 1) * min
            l += 1
        elsif r == min_i
            ans += (min_i - l + 1) * min
            r -= 1
        else
            ans += (r - min_i + 1) * (min_i - l + 1) * min
            ls.push(min_i + 1)
            rs.push(r)
            #ls.push(l)
            #rs.push(min_i - 1)
            r = min_i - 1
        end
    end
end

puts ans
#p Time.now - t