This page is still under construction.

Parts of this page are still being built. What you see may change.

Permutations on the Road: Alice

Interview

Time limit3sMemory limit1024 MB

Summary
Given a permutation, sum the number of inversions over every contiguous subarray. Each inversion pair contributes once for every subarray that contains both positions.
Level

Medium5 of 10

Topics
Array, Combinatorics, Prefix sum, Math
Solved
No attempts yet

Problem

Alice and Bob frequently take long road trips to get to various programming competitions in their area. Since everything is bigger in the state they live in, they have turned to playing car games to pass the time.

Alice and Bob are both computer scientists, so they quickly tired of "guess the number", since the guesser could always identify the number using a logarithmic number of guesses. To raise the challenge, they created a new game: "guess the permutation".

A permutation of length NN is an arrangement of the numbers 1,…,N1, \dots, N. For a given permutation PP, define inv(l,r)\text{inv}(l, r) to be the number of pairs (i,j)(i, j) with l≤i≤j≤rl \leq i \leq j \leq r such that Pi>PjP_i > P_j.

When playing this game, Alice thinks of a permutation, and Bob can ask Alice for the result of the function inv\text{inv} for up to NN inputs.

Alice has already thought of her permutation PP. As she mindlessly answers all of Bob's queries, she thinks of a different problem: What is the sum of inv(l,r)\text{inv}(l, r) over all values of ll and rr?

Input

The first line of input contains a single integer NN (1≤N≤100 0001 \leq N \leq 100\,000), the length of the permutation. The second line of input contains NN space-separated integers, Alice's permutation PP.

Output

Output a single integer, the sum of inv(l,r)\text{inv}(l, r) over all values of ll and rr. The answer is guaranteed to fit in a signed 6464-bit integer.

Hint

In the first sample case, there are no inversions.

In the second sample case,

  • inv(1,1)=0\text{inv}(1, 1) = 0.
  • inv(1,2)=0\text{inv}(1, 2) = 0.
  • inv(1,3)=1\text{inv}(1, 3) = 1.
  • inv(2,2)=0\text{inv}(2, 2) = 0.
  • inv(2,3)=1\text{inv}(2, 3) = 1.
  • inv(3,3)=0\text{inv}(3, 3) = 0.

Summing these values gives 22.

Examples2

  1. Example 1

    Input
    3
    1 2 3
    
    Expected output
    0
    
  2. Example 2

    Input
    3
    1 3 2
    
    Expected output
    2