-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count Inversions.cpp
68 lines (59 loc) · 1.41 KB
/
Count Inversions.cpp
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
59
60
61
62
63
64
65
66
67
68
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
long long merge(long long arr[],long long l,long long m,long long r){
long long a=l,b=m+1;
vector<long long> v;
long long i=0;
while(a<=m && b<=r){
if(arr[a]>arr[b]){
v.push_back(arr[b]);
b++;
i+=(m-a+1);
}else{
v.push_back(arr[a]);
a++;
}
}
while(a<=m){
v.push_back(arr[a]);
a++;
}
while(b<=r){
v.push_back(arr[b]);
b++;
}
for(int i=l;i<=r;i++){
arr[i]=v[i-l];
}
return i;
}
long long mergesort(long long arr[], long long l, long long r){
long long i=0;
if(l>=r) return i;
long long m = l+(r-l)/2;
i+=mergesort(arr,l,m);
i+=mergesort(arr,m+1,r);
i+=merge(arr,l,m,r);
return i;
}
long long int inversionCount(long long arr[], long long N){
return mergesort(arr,0,N-1);
}
};
int main() {
long long T;
cin >> T;
while(T--){
long long N;
cin >> N;
long long A[N];
for(long long i = 0;i<N;i++){
cin >> A[i];
}
Solution obj;
cout << obj.inversionCount(A,N) << endl;
}
return 0;
}