AcWing 788. 逆序对的数量
原题链接
简单
作者:
ls131
,
2020-05-10 15:46:05
,
所有人可见
,
阅读 559
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
const int N=1e5+10;
int q[N],tmp[N]; //temporary暂时的
LL merge_sort(int q[],int l,int r){
if(l>=r) return 0;
int mid=l+r>>1;
LL res =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 {
res+=mid-i+1;
tmp[k++]=q[j++];
}
}
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];
return res;
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++) scanf("%d",&q[i]);
cout<< merge_sort(q,0,n-1)<<endl;
return 0;
}