目录
题目链接
788. 逆序对的数量 - AcWing题库
一些话
//注意cnt要开long long,最大是n方
流程
在原归并排序的这部分做修改,else时加一个cnt += mid - i + 1即可
while(i <= mid && j <= r) {
if(q[i] <= q[j]) tmp[k++] = q[i++];
else tmp[k++] = q[j++],cnt += mid - i + 1;
}
套路
ac代码
[//]: # (打卡模板,上面预览按钮可以展示预览效果 ^^)
```
//注意cnt要开long long,最大是n方
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
const int N = 1e5 + 10;
int tmp[N],q[N];
int n;
long long cnt = 0;
void merge_sort(int q[],int l,int r){
if(l >= r) return ;
int mid = l + r >> 1;
merge_sort(q,l,mid);
merge_sort(q,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++],cnt += mid - i + 1;
}
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];
}
}
int main(){
cin >> n;
for(int i = 0;i < n;i++){
scanf("%d",&q[i]);
}
merge_sort(q,0,n-1);
cout << cnt << endl;
}
```