Almost Sorted

MEDIUM
G
Time limit: 2.0sMemory limit: 256MB
divide-and-conquersortingfenwick-tree

Almost Sorted

Given an array of n integers, find the minimum number of adjacent swaps ​‌‌‌​‌​‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​‌‌​​​​‌​​‌‌‌​‌​​‌‌​​​‌‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​​‌‌‌​‌​​‌‌‌​​​​​​‌‌‌‌​‌​​‌‌‌​​​​‌‌​​‌​​​​‌‌​​​‌​​‌‌​‌‌​​‌‌​​‌​​​​‌‌‌​​‌​​‌‌‌​​‌​‌‌​​​​‌​​‌‌‌​‌​​‌‌‌​‌​​​​‌‌‌‌​‌​​‌‌​​​‌​​‌‌​‌‌‌​​‌‌‌​​‌​​‌‌​​‌​​​‌‌‌​​​​​‌‌​​‌‌​​‌‌​‌‌‌​​‌‌​‌‌‌​​‌‌​‌​‌​​‌‌​‌‌​​​‌‌​​‌‌​​‌‌‌​​​​​‌‌​​‌‌needed to sort it in non-decreasing order. (This is a classic fact: that minimum equals the number of inversions — pairs i < j with a[i] > a[j].)

Input

Line 1: integer n (1 ≤ n ≤ 2·10^5) Line 2: n integers ​‌‌‌​‌​‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​‌‌​​​​‌​​‌‌‌​‌​​‌‌​​​‌‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​​‌‌‌​‌​​‌‌‌​​​​​​‌‌‌‌​‌​​‌‌‌​​​​‌‌​​‌​​​​‌‌​​​‌​​‌‌​‌‌​​‌‌​​‌​​​​‌‌‌​​‌​​‌‌‌​​‌​‌‌​​​​‌​​‌‌‌​‌​​‌‌‌​‌​​​​‌‌‌‌​‌​​‌‌​​​‌​​‌‌​‌‌‌​​‌‌‌​​‌​​‌‌​​‌​​​‌‌‌​​​​​‌‌​​‌‌​​‌‌​‌‌‌​​‌‌​‌‌‌​​‌‌​‌​‌​​‌‌​‌‌​​​‌‌​​‌‌​​‌‌‌​​​​​‌‌​​‌‌a_1 … a_n (-10^9 ≤ a_i ≤ 10^9)

Output

A single integer: the minimum number of adjacent swaps to sort the array.

Example

Input:

5
5 4 3 2 1

Output:

10

Constraints

  • 1 ≤ n ≤ 2·10^5 ​‌‌‌​‌​‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​‌‌​​​​‌​​‌‌‌​‌​​‌‌​​​‌‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​​‌‌‌​‌​​‌‌‌​​​​​​‌‌‌‌​‌​​‌‌‌​​​​‌‌​​‌​​​​‌‌​​​‌​​‌‌​‌‌​​‌‌​​‌​​​​‌‌‌​​‌​​‌‌‌​​‌​‌‌​​​​‌​​‌‌‌​‌​​‌‌‌​‌​​​​‌‌‌‌​‌​​‌‌​​​‌​​‌‌​‌‌‌​​‌‌‌​​‌​​‌‌​​‌​​​‌‌‌​​​​​‌‌​​‌‌​​‌‌​‌‌‌​​‌‌​‌‌‌​​‌‌​‌​‌​​‌‌​‌‌​​​‌‌​​‌‌​​‌‌‌​​​​​‌‌​​‌‌- The answer may exceed the range of a 32-bit signed integer — use a 64-bit type. ​‌‌‌​‌​‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​‌‌​​​​‌​​‌‌‌​‌​​‌‌​​​‌‌​​‌‌‌‌​‌​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌‌​​‌‌‌​‌​​​‌‌​​‌​‌​‌‌‌​​‌‌​‌‌‌​‌​​​​‌‌‌​‌​​‌‌‌​​​​​​‌‌‌‌​‌​​‌‌‌​​​​‌‌​​‌​​​​‌‌​​​‌​​‌‌​‌‌​​‌‌​​‌​​​​‌‌‌​​‌​​‌‌‌​​‌​‌‌​​​​‌​​‌‌‌​‌​​‌‌‌​‌​​​​‌‌‌‌​‌​​‌‌​​​‌​​‌‌​‌‌‌​​‌‌‌​​‌​​‌‌​​‌​​​‌‌‌​​​​​‌‌​​‌‌​​‌‌​‌‌‌​​‌‌​‌‌‌​​‌‌​‌​‌​​‌‌​‌‌​​​‌‌​​‌‌​​‌‌‌​​​​​‌‌​​‌‌

Sample Testcases

Case 1

Input
5
5 4 3 2 1
Expected Output
10

Case 2

Input
5
1 2 3 4 5
Expected Output
0
Loading Cloud IDE...
Ln 1, Col 1Spaces: 4UTF-8
pythonAuto-Saved

Input

5
5 4 3 2 1

Expected Output

10

Run or submit your code to see output here.