forked from BabesGotByte/Coding_SkillSet_Topicwise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnswer10.cpp
64 lines (44 loc) · 1.1 KB
/
Answer10.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
ass Solution{
public:
// arr[]: Input Array
// N : Size of the Array arr[]
// Function to count inversions in the array.
#define ll long long
ll merge(ll arr[], ll lo, ll mi, ll hi){
ll n1 = mi - lo + 1;
ll n2 = hi - mi;
ll a[n1], b[n2];
for(ll i = 0; i < n1; i++)
a[i] = arr[lo + i];
for(ll i = 0; i < n2; i++)
b[i] = arr[mi + 1 + i];
ll i = 0, j = 0, k = lo;
ll in = 0;
while(i < n1 && j < n2){
if(a[i] <= b[j])
arr[k++] = a[i++];
else{
arr[k++] = b[j++];
in += n1 - i; /* inversion count */
}
}
while(i < n1)
arr[k++] = a[i++];
while(j < n2)
arr[k++] = b[j++];
return in;
}
ll mergeSort(ll arr[], ll lo, ll hi){
ll in = 0;
if(lo >= hi)
return 0;
ll mi = (lo + hi)/2;
in += mergeSort(arr, lo, mi);
in += mergeSort(arr, mi + 1, hi);
in += merge(arr, lo, mi, hi);
return in;
}
ll inversionCount(ll A[], ll n){
return mergeSort(A, 0, n-1);
}
};