#include<iostream>
using namespace std;
const int N = 100010;
int n;
int q[N],tmp[N];
long long merge_sort(int l,int r){
if(l>=r) return 0;
int mid = l+r>>1;
long long 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 tmp[k++] = q[j++],res += mid - i + 1;
}
while(i<=mid) tmp[k++] = q[i++];
while(j<=r) tmp[k++] = q[j++];
for(i=l,k=0;i<=r;i++,k++) q[i] = tmp[k];
return res;
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&q[i]);
long long res = merge_sort(0,n-1);
printf("%lld",res);
}
求解逆序对的数量(c++实现)
最新推荐文章于 2024-06-15 11:02:58 发布