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 Haskell (GHC 7.10.3) (judge verdict: Time Limit Exceeded)

{-# LANGUAGE MultiWayIf #-}
import qualified Data.Vector as V
import qualified Data.ByteString.Char8 as BS
import Data.Maybe

count :: Int -> Int -> Int
count n i = sum [ minimum [i, l, n-i+1, n-l+1] | l <- [1..n] ]

solve :: V.Vector Int -> Int
solve v = if
  | v == V.fromList [1..n] -> n * (n+1) * (n+2) `div` 6
  | V.null v -> 0
  | otherwise -> mv * count n (m+1) + solve l + solve (V.tail r)
  where
    n = V.length v
    m = V.minIndex v
    mv = v V.! m
    (l, r) = V.splitAt m v

main :: IO ()
main = do
  getLine
  a <- V.fromList . map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine
  print $ solve a