AcWing 788. 逆序对的数量
原题链接
简单
作者:
cjyasleep
,
2021-03-15 21:26:44
,
所有人可见
,
阅读 266
#include<iostream>
using namespace std;
int n,q[100000],temp[100000];
long long ans;
long long merge_sort(int q[],int l,int r){
if(l>=r)return 0;
int i=l,mid=l+r>>1,j=mid+1,k=0;
merge_sort(q,l,mid),merge_sort(q,mid+1,r);
while(i<=mid&&j<=r){
if(q[i]<=q[j])temp[k++]=q[i++];
else {
temp[k++]=q[j++];
ans+=mid-i+1;
}
}
while(i<=mid)temp[k++]=q[i++];
while(j<=r)temp[k++]=q[j++];
for(i=l,j=0;i<=r;)q[i++]=temp[j++];
}
int main(){
cin>>n;
for(int i=0;i<n;i++)scanf("%d",q+i);
merge_sort(q,0,n-1);
cout<<ans;
return 0;
}