-2

a1, a2, ..., an sequence numbers are given. Now, give an algorithm with O(nlg n) running time to calculate the number of pairs (i, j) for i < j and ai > aj.

Input: The number of test cases has came in first. For each test case number has came n number for first and then a1, a2, ..., an in the next line. N <= 100000

ai <= 100000000

Now, I want the output as follows:

Output: For each test is printed only one number (that is the asked value in the beginning of the question).

Sample Input:

2
4
3 2 1 5
5

8 9 3 2 1

Sample Output:

3

9
MRS1367
  • 1,053
  • 1
  • 14
  • 40
maryam
  • 1,437
  • 2
  • 18
  • 40

1 Answers1

4

This is a standard algorithm problem known as "Inversion count". I will just give you the primary source rather than explaining from scratch. Check this link. The key things are-

i) You just divide the array into 2 equal part.

ii) Then get the answer for both the part.

iii) When merging just you need to consider how may numbers in the left segment is smaller than right segment. That is what added finally to the answer.

iv) return it.

That's it. You have to perform all the operations that you would do in a merge sort. Along with that you just need to correctly determine the number of inversions during merge operation.

user2736738
  • 30,591
  • 5
  • 42
  • 56