forked from love1024/spoj-solution-with-explanation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CODESPTB.cpp
61 lines (51 loc) · 998 Bytes
/
CODESPTB.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
#include<bits/stdc++.h>
using namespace std;
long long inv = 0;
void mergeArray(int arr[],int s,int m,int e) {
int i = s,j = m+1,k=0;
int temp[e-s+1];
while(i <= m && j <= e) {
if(arr[i] <= arr[j]) {
temp[k] = arr[i];
i++;
} else {
temp[k] = arr[j];
j++;
inv += (m-i+1);
}
k++;
}
while(i <= m) {
temp[k] = arr[i];
i++,k++;
}
while(j <= e) {
temp[k] = arr[j];
j++,k++;
}
for(int i=0;i<=e-s;i++) {
arr[i+s] = temp[i];
}
}
void mergeSort(int arr[],int i,int j) {
if(i >= j)
return;
int m = (i+j)/2;
mergeSort(arr,i,m);
mergeSort(arr,m+1,j);
mergeArray(arr,i,m,j);
}
int main()
{
int t,n;
cin>>t;
while(t--) {
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
inv = 0;
mergeSort(arr,0,n-1);
cout<<inv<<endl;
}
}