归并排序-逆序对的数量
原理
略
代码
#include<iostream>
using namespace std;
const int N = 1e5 + 10;
typedef unsigned long long ULL;
int s[N], tmp[N];
ULL mergeSort(int l, int r){
if(l >= r) return 0;
int mid = (l + r) >> 1;
ULL res = mergeSort(l, mid) + mergeSort(mid + 1, r);
int i = l, j = mid + 1, k = 0;
while(i <= mid && j <= r){
if(s[i] <= s[j]) tmp[k++] = s[i++];
else {
res += mid - i + 1;
tmp[k++] = s[j++];
}
}
while(i <= mid) tmp[k++] = s[i++];
while(j <= r) tmp[k++] = s[j++];
for(k = 0; l <= r;) s[l++] = tmp[k++];
return res;
}
int main(){
int n;
cin >> n;
for(int i = 0; i < n; i++) cin >> s[i];
cout << mergeSort(0, n - 1);
return 0;
}
Q&A
以4 3 2 1为例,手动模拟即可明白这个代码
标签:mergeSort,归并,int,mid,ULL,排序,逆序 From: https://www.cnblogs.com/INnoVationv2/p/17510941.html