逆序对
分析
见《进阶指南》第37
页。
实现
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 500010;
int n, a[N], temp[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 i = l, j = mid + 1, k = l;
while (i <= mid && j <= r) {
if (a[i] <= a[j]) {
temp[k ++] = a[i ++];
} else {
temp[k ++] = a[j ++];
res += mid - i + 1;
}
}
while (i <= mid) temp[k ++] = a[i ++];
while (j <= r) temp[k ++] = a[j ++];
for (int i = l; i <= r; ++ i) a[i] = temp[i];
return res;
}
int main () {
scanf("%d", &n);
for (int i = 1; i <= n; ++ i) scanf("%d", &a[i]);
printf("%lld", merge_sort(1, n));
return 0;
}