Number of inversions
Time: 1 s · Memory: 256 MB
- Sorting
Statement
You are given an array of integers. It must be sorted in increasing order by swapping only adjacent elements. What is the minimum number of swaps?
Input format
The first line contains (). The second line contains integers ().
Output format
A single number — the minimum number of swaps.
Examples
Input
3 3 1 2
Output
2
Input
5 9 1 0 5 4
Output
6
Note
Every adjacent swap removes exactly one inversion — a pair with , so the answer is the number of inversions. Count them inside merge sort: when merging two sorted halves takes an element from the right half, all remaining elements of the left half are greater — add that many inversions. This is ; simulating bubble sort is .
Equal elements form no inversion: on a tie take from the left half. The answer reaches — a 64-bit type is needed. In the second example the answer is .
Source: UVa 10810.
