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)

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.null v then 0 else mv * count (V.length v) (m+1) + solve l + solve (V.tail r)
  where
    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
  let n = V.length a
  print $ if a == V.fromList [1..n] || a == V.fromList [n, n-1..1]
    then n * (n+1) * (n+2) `div` 6
    else solve a