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: Time Limit Exceeded)

#![allow(unused_imports)]
#![allow(non_snake_case)]
use std::cmp::*;
use std::collections::*;
use std::io::Write;

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

fn main() {
    let n: usize = read();
    let a: Vec<i64> = read_vec();
    let mut pos = vec![0; n + 1];
    for i in 0..n {
        pos[a[i] as usize] = i;
    }

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

    let mut ans = 0i64;
    for i in (1..n + 1).rev() {
        let x = pos[i];
        let v = x as i64;
        let n = nr[x];
        let p = pr[x];
        ans += i as i64 * (v - p as i64) * (n as i64 - v);

        if n >= 0 {
            pr[n as usize] = p;
        }
        if p >= 0 {
            nr[p as usize] = n;
        }
        debug!(pr, nr);
    }
    println!("{}", ans);
}
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}