-
Notifications
You must be signed in to change notification settings - Fork 6
/
Solution.java
58 lines (46 loc) · 1.34 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
* DeveloperName(): Jignesh Chudasama
* GithubName(): https://github.com/Jignesh-81726
*/
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int d = sc.nextInt();
for (int tc = 0; tc < d; tc++) {
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
System.out.println(countInversions(a, 0, a.length - 1));
}
sc.close();
}
static long countInversions(int[] a, int beginIndex, int endIndex) {
if (beginIndex >= endIndex) {
return 0;
}
long inversionNum = 0;
int middleIndex = (beginIndex + endIndex) / 2;
inversionNum += countInversions(a, beginIndex, middleIndex);
inversionNum += countInversions(a, middleIndex + 1, endIndex);
int leftIndex = beginIndex;
int rightIndex = middleIndex + 1;
int[] sorted = new int[endIndex - beginIndex + 1];
for (int i = 0; i < sorted.length; i++) {
if (rightIndex > endIndex || (leftIndex <= middleIndex && a[leftIndex] <= a[rightIndex])) {
sorted[i] = a[leftIndex];
leftIndex++;
} else {
inversionNum += middleIndex - leftIndex + 1;
sorted[i] = a[rightIndex];
rightIndex++;
}
}
for (int i = beginIndex; i <= endIndex; i++) {
a[i] = sorted[i - beginIndex];
}
return inversionNum;
}
}