All problems

Problem 44

Count Inversions

Hard · 30 pts · Array, Sorting, Divide and Conquer

Problem

An inversion in an array is a pair of positions i < j where the earlier element is larger than the later one: A[i] > A[j]. The number of inversions measures how far the array is from being sorted; a sorted array has none. Count the inversions in an array of N integers. Checking every pair takes O(N²), too slow for N = 100,000. Modify merge sort instead: when merging two sorted halves, each time an element from the right half is placed before the remaining elements of the left half, it forms an inversion with each of them. The answer can exceed the 32-bit range.

Input

First line: integer N. Second line: N space-separated integers.

Output

Print the number of inversions.

Constraints

1 <= N <= 100000; -1000000000 <= A[i] <= 1000000000

Example input

5
2 4 1 3 5

Example output

3

Explanation

In 2 4 1 3 5, the pairs where a larger value comes first are (2, 1), (4, 1) and (4, 3). Every other pair is in order, so there are 3 inversions.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Merge Intervals Next: Minimum Size Subarray Sum