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 Rust (1.15.1) (judge verdict: Accepted)

fn solve(n: &str) -> usize {
    let n: usize = n.parse().unwrap();
    let mut a = String::new();
    std::io::stdin().read_line(&mut a).unwrap();
    let a: Vec<usize> = a.split_whitespace().map(|x|x.parse().unwrap()).collect();
    let mut p = vec![0;n+1];
    let mut l = vec![0;n+2];
    let mut r = vec![n+1;n+2];
    for i in 0..n {
        let v = a[i];
        p[v] = i+1;
        l[i+1] = i;
        r[i+1] = i+2;
    }
    let p=p;
    let mut t=0;
    for v in (1..n+1).rev() {
        let i = p[v];
        t=t+v*(r[i]-i)*(i-l[i]);
        l[r[i]]=l[i];
        r[l[i]]=r[i];
    }
    t
}
fn main() {
    loop {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let s = s.trim_right();
        if s=="" { break; }
        println!("{}",solve(&s));
    }
}