-
Notifications
You must be signed in to change notification settings - Fork 0
/
788逆序对的数量.cpp
47 lines (45 loc) · 856 Bytes
/
788逆序对的数量.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
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 10 + 1e5;
int n;
int q[N], tmp[N];
LL merge_sort(int l, int r)
{
if (l == r)
return 0;
int mid = l + r >> 1;
LL res = merge_sort(l, mid) + merge_sort(mid + 1, r);
int k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r)
{
if (q[i] <= q[j])
tmp[k++] = q[i++];
else
{
tmp[k++] = q[j++];
res += mid - i + 1;
}
}
while (i <= mid)
{
tmp[k++] = q[i++];
}
while (j <= r)
tmp[k++] = q[j++];
for (i = l, j = 0; i <= r; i++, j++)
{
q[i] = tmp[j];
}
return res;
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &q[i]);
}
printf("%lld", merge_sort(0, n - 1));
return 0;
}