Problem 519
Reverse Pairs
Hard · 30 pts · Array, Divide and Conquer, Merge Sort
Problem
A reverse pair is a pair of positions i < j with A[i] > 2 × A[j]. Count the reverse pairs in the array. Checking every pair is O(N²), too slow for N = 50,000. Use merge sort: before merging two sorted halves, move a pointer through the right half to count, for each element of the left half, how many right elements are less than half of it. Values can be negative, so compare A[i] > 2 × A[j] directly using 64-bit integers.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].
Output
Print the number of reverse pairs.
Constraints
1 <= N <= 50000; -2^31 <= A[i] <= 2^31 - 1
Example input
5 1 3 2 3 1
Example output
2
Explanation
In 1 3 2 3 1, the pairs where the earlier value is more than twice the later one are (3, 1) using the first 3 and the last 1, and (3, 1) using the second 3. So the answer is 2.