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)


use std::io;
use std::cmp;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::HashSet;

fn read_line() -> String {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).ok();
    buf
}


fn main() {
    let n: usize = read_line().trim().parse().unwrap();
    let a: Vec<i64> = read_line().split_whitespace().map(|s| s.parse().unwrap()).collect();

    let mut pos = HashMap::new();
    for i in 0..n {
        pos.insert(a[i], i);
    }

    let mut ans = 0i64;

    let mut pr = vec![0i32; n+1];
    let mut nr = vec![0i32; n+1];
    for i in 0..n {
        pr[i] = i as i32 -1;
        nr[i] = i as i32 +1;
    }

    for i in (1i64..(n+1) as i64).rev() {
        let x = pos.get(&i).unwrap();
        let v = *x as i64;
        let n = nr[*x];
        let p = pr[*x];
        ans += i * (v - p as i64) * (n as i64 - v);
        
        if (n >= 0) {
            pr[n as usize] = p;
        }
        if (p >= 0) {
            nr[p as usize] = n;
        }
    }

    println!("{}", ans);
}