let printf = Printf.printf
let scanf = Scanf.scanf

module Array = struct
  include Array

  let create x ~len = make len x
end

module List = struct
  include List

  let rec repf' ~init ~n ~f =
    if n = 0 then init else repf' ~init:(f () :: init) ~f ~n:(n-1)

  let repf ~n ~f =
    assert (n >= 0);
    rev (repf' ~init:[] ~f ~n)

  let rec iteri' i t ~f =
    match t with
    | [] -> ()
    | hd::tl ->
      f i hd;
      iteri' (i+1) tl ~f

  let iteri t ~f = iteri' 0 t ~f

  let rec range' acc stride start_i stop_i =
    if (stop_i - start_i) * stride <= 0 then acc
    else
      range' (start_i::acc) stride (start_i + stride) stop_i

  let range ?(stride=1) start_i stop_i =
    rev (range' [] stride start_i stop_i)

  let fold t ~init ~f = fold_left f init t
end

module Fn = struct
  let id x = x
end

let () =
  scanf "%d " (fun n ->
      let aa = List.repf ~n ~f:(fun () -> scanf "%d " Fn.id) in
      let idxs = Array.create ~len:(n+1) 0 in
      List.iteri aa ~f:(fun i a -> idxs.(a) <- i);
      let ranges = Array.create ~len:(n+2) (0,0) in
      for i = 0 to n-1 do ranges.(i+1) <- (i,i) done;

      let ks = List.range ~stride:(-1) n 0 in
      let ans = List.fold ks ~init:0 ~f:(fun acc k ->
          let idx = idxs.(k) in
          let (l,r) = ranges.(idx+1) in
          let (l_of_l,_), (_,r_of_r) = ranges.(l), ranges.(r+2) in
          ranges.(l) <- (l_of_l, r);
          ranges.(r+2) <- (l, r_of_r);
          acc + k * (idx-l + 1) * (r-idx + 1)
        )
      in
      printf "%d\n" ans
    )
