-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinversions.cpp
More file actions
76 lines (59 loc) · 1.87 KB
/
inversions.cpp
File metadata and controls
76 lines (59 loc) · 1.87 KB
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
69
70
71
72
73
74
75
#include <bits/stdc++.h>
using namespace std;
#define MAINRET(x) in##x
#define what_is(x) cout << #x << " is " << x << endl;
#define print_vec(x, n) for (int i = 0; i < n; i++) cout << x[i] << ' '; cout << endl;
#define LL long long
#define arr2 array<int,2>
#define arr3 array<int,3>
void solve();
MAINRET(t) main(void) {
std::cin.tie(nullptr);
std::cin.sync_with_stdio(false);
solve();
}
constexpr int INF = (int)1e9 + 100;
constexpr LL LINF = std::numeric_limits<LL>::max() / 2;
constexpr int NINF = -INF;
constexpr int MX = 2 * 1e5 + 1;
constexpr int MD = (int)1e9 + 7;
int n, m, k;
class Inversions {
private:
long long mergeAndCount(vector<LL>& arr, vector<LL>& temp, LL left, LL mid, LL right) {
LL i = left;
LL j = mid + 1;
LL k = left;
long long inv_count = 0;
while ((i <= mid) && (j <= right)) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
inv_count += (mid - i + 1);
}
}
while (i <= mid)
temp[k++] = arr[i++];
while (j <= right)
temp[k++] = arr[j++];
for (i = left; i <= right; i++)
arr[i] = temp[i];
return inv_count;
}
long long mergeSortAndCount(vector<LL>& arr, vector<LL>& temp, LL left, LL right) {
long long inv_count = 0;
if (left < right) {
LL mid = (left + right) / 2;
inv_count += mergeSortAndCount(arr, temp, left, mid);
inv_count += mergeSortAndCount(arr, temp, mid + 1, right);
inv_count += mergeAndCount(arr, temp, left, mid, right);
}
return inv_count;
}
public:
long long countInversions(vector<LL>& arr) {
vector<LL> temp(arr.size());
return mergeSortAndCount(arr, temp, 0, arr.size() - 1);
}
};