merge_sort(l, r)
返回区间[l, r]内逆序对的个数,而区间[l, r]内的逆序对个数是左半边的逆序对个数merge_sort(l, mid)
和右半边逆序对个数merge_sort(mid + 1, r)
之和外加左右两边构成的逆序对个数。
#include <iostream>
using namespace std;
const int N = 100010;
#define LL long long
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 i = l, j = mid + 1, k = 0;
while(i <= mid && j <= r)
if(q[i] <= q[j]) tmp[k ++] = q[i ++];
else{
res += mid - i + 1; // 1
tmp[k ++] = q[j ++];
}
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(){
cin >> n;
for(int i = 0; i < n; i ++) cin >> q[i];
cout << merge_sort(0, n - 1);
return 0;
}
注意:1处不能写成j - mid
,否则会出现下面的情况