-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathInversionCount.cpp
More file actions
64 lines (52 loc) · 921 Bytes
/
InversionCount.cpp
File metadata and controls
64 lines (52 loc) · 921 Bytes
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
#include<iostream>
#include<cstdio>
using namespace std;
long long count;
int temp[200000];
int arr[200000];
void countInversions(int arr[],int low,int high);
void merge(int arr[],int low,int mid,int high);
void countInversions(int arr[],int low,int high){
int mid;
if(low<high){
mid = low + (high-low)/2;
countInversions(arr,low,mid);
countInversions(arr,mid+1,high);
merge(arr,low,mid,high);
}
}
void merge(int arr[],int low,int mid,int high){
int i , j , k ;
i=low;
k=low;
j=mid+1;
while(i<=mid&&j<=high){
if(arr[i]<arr[j]){
temp[k++] = arr[i++];
}
else{
temp[k++]=arr[j++];
count+= mid - i + 1;
}
}
while(i<=mid){
temp[k++] = arr[i++];
}
while(j<=high){
temp[k++] = arr[j++];
}
for(i=low;i<k;i++) arr[i] = temp[i];
}
int main(){
int i,t,n;
cin>>t;
while(t--){
cin>>n;
for(i=0;i<n;i++)
{ scanf("%d",&arr[i]); }
count = 0 ;
countInversions(arr,0,n-1);
printf("%lld\n",count);
}
return 0;
}