归并排序-分治法求序列逆序对数量
核心思想
1. 序列的逆序对可以分成3类,两个数都在mid 左边,两个数都在mid右边,或者一左一右
2. 对于一左一右的,根据归并排序的过程,可以很容易求的
3. 最后返回总的逆序对数量即可
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int q[N], tmp[N];
typedef long long LL; // ⚠️可能会爆int
LL merge_sort(int *q, int l, int r) {
if (l >= r) return 0;
int mid = (l + r) >> 1;
int k = 0, i = l, j = mid + 1;
LL res = merge_sort(q, l, mid);
res += merge_sort(q, mid + 1, r);
while (i <= mid && j <= r) {
if (q[i] <= q[j]) tmp[k++] = q[i++];
else {
tmp[k++] = q[j++];
res += mid - i + 1; // 当q[i] > q[j] 时,那么i~mid中间的这些数均大于q[j]
}
}
while (i <= mid) tmp[k++] = q[i++];
while (j <= r) tmp[k++] = q[j++];
for (int i = l, j = 0; i <= r; i++, j++) q[i] = tmp[j];
return res;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> q[i];
cout << merge_sort(q, 0, n - 1) << endl;
return 0;
}
大佬!!!!!!