-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinversions.cpp
59 lines (55 loc) · 1.12 KB
/
inversions.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
#include <bits/stdc++.h>
using namespace std;
int merge(vector<int> & nums, int i, int m, int j, vector<int> & tmp){
int pos1 = i, pos2 = m, pos3 = i;
int ans = 0;
while(pos1 < m && pos2 <= j){
if(nums[pos1] <= nums[pos2]){
tmp[pos3++] = nums[pos1++];
}else{
tmp[pos3++] = nums[pos2++];
ans += m - pos1;
}
}
while(pos1 < m){
tmp[pos3++] = nums[pos1++];
}
while(pos2 <= j){
tmp[pos3++] = nums[pos2++];
}
for(int pos = i; pos <= j; pos++){
nums[pos] = tmp[pos];
}
return ans;
}
int inversions(vector<int> & nums, int i, int j, vector<int> & tmp){
int ans = 0;
if(i < j){
int m = i + ((j - i) >> 1);
ans += inversions(nums, i, m, tmp);
ans += inversions(nums, m + 1, j, tmp);
ans += merge(nums, i, m + 1, j, tmp);
}
return ans;
}
int inversions(vector<int> & nums){
int ans = 0;
int n = nums.size();
for(int i = 0; i < n - 1; i++){
for(int j = i + 1; j < n; j++){
if(nums[i] > nums[j]) ans++;
}
}
return ans;
}
int main(){
vector<int> nums;
int num;
while(cin >> num){
nums.push_back(num);
}
int n = nums.size();
vector<int> tmp(n);
cout << inversions(nums) << "\n";
return 0;
}