题目:
题解:
在每次归并排序合并的时候计算逆序对数量。
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int q[100010];
int tmp[100010];
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 k=0,i=l,j=mid+1;
while(i<=mid&&j<=r){
if(q[i]>q[j]){
tmp[k++]=q[j++];
res += mid-i+1;
}else {
tmp[k++]=q[i++];
}
}
while(i<=mid)tmp[k++]=q[i++];
while(j<=r)tmp[k++]=q[j++];
for(i=l,j=0;i<=r;j++,i++)q[i]=tmp[j];
return res;
}
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)scanf("%d",q+i);
printf("%lld",merge_sort(0,n-1));
}