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
|
#include <iostream>
#include <vector>
using std::vector;
using std::swap;
long long get_number_of_inversions(vector<int> &a, vector<int> &b, size_t left, size_t right)
{
long long number_of_inversions = 0;
if (right <= left + 1) return number_of_inversions;
size_t ave = left + (right - left) / 2;
number_of_inversions += get_number_of_inversions(a, b, left, ave);
number_of_inversions += get_number_of_inversions(a, b, ave, right);
size_t i = left, j = ave, k = left;
while ((i != ave) && (j != right)) {
if (a[i] <= a[j]) {
b[k] = a[i];
i++;
} else {
b[k] = a[j];
j++;
number_of_inversions += (ave - i);
}
k++;
}
for( ; i != ave; i++, k++)
b[k] = a[i];
for( ; j != right; j++, k++)
b[k] = a[j];
for(i = left, k = left; i < right; i++, k++)
a[i] = b[k];
return number_of_inversions;
}
int main() {
int n;
std::cin >> n;
vector<int> a(n);
for (size_t i = 0; i < a.size(); i++) {
std::cin >> a[i];
}
vector<int> b(a.size());
std::cout << get_number_of_inversions(a, b, 0, a.size()) << '\n';
}
|