-
Notifications
You must be signed in to change notification settings - Fork 2
/
Inversion count with merge sort.cpp
58 lines (58 loc) · 1.16 KB
/
Inversion count with merge sort.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
#include <iostream>
uint64_t Merge(uint64_t v[], uint64_t aux[], uint32_t l, uint32_t mid, uint32_t r) {
uint64_t nrInv = 0;
uint32_t i = l, j = mid, k = l;
while (i < mid and j <= r) {
if (v[i] <= v[j]) {
aux[k] = v[i];
++ i;
}
else {
aux[k] = v[j];
++ j;
nrInv += mid - i;
}
++ k;
}
while (i < mid) {
aux[k] = v[i];
++ i;
++ k;
}
while (j <= r) {
aux[k] = v[j];
++ j;
++ k;
}
for (i = l; i <= r; ++ i)
v[i] = aux[i];
return nrInv;
}
uint64_t mergeSort(uint64_t v[], uint64_t aux[], uint32_t l, uint32_t r) {
uint64_t nrInv = 0;
if (l < r) {
uint32_t mid = (l + r) >> 1;
nrInv += mergeSort(v, aux, l, mid);
nrInv += mergeSort(v, aux, mid + 1, r);
nrInv += Merge(v, aux, l, mid + 1, r);
}
return nrInv;
}
uint64_t countInversions(uint32_t n, uint64_t v[]) {
uint64_t Copy[n];
for (uint32_t i = 0; i < n; ++ i)
Copy[i] = v[i];
uint64_t aux[n];
return mergeSort(Copy, aux, 0, n - 1);
}
int main() {
std :: ios_base :: sync_with_stdio(false);
std :: cin.tie(nullptr);
uint32_t n, i;
std :: cin >> n;
uint64_t v[n];
for (i = 0; i < n; ++ i)
std :: cin >> i;
std :: cout << countInversions(n, v);
return 0;
}