Scanf.scanf "%d" (fun n ->
    let p = Array.make n 0 in
    for i = 0 to n - 1 do
        Scanf.scanf " %d" (fun a -> p.(a - 1) <- i)
    done;

    let module S = Set.Make (struct type t = int let compare = compare end) in

    let rec loop i set acc =
        if i = n then acc else
            let l, _, r = S.split p.(i) set in
            let mx = S.max_elt l in
            let mi = S.min_elt r in
            loop (i + 1) (S.add p.(i) set) (acc + (i + 1) * (p.(i) - mx) * (mi - p.(i)))
    in
    loop 0 (S.add (-1) (S.singleton n)) 0 |> Printf.printf "%d\n"
)