AcWing 788. 逆序对的数量
原题链接
简单
作者:
yvr
,
2021-05-26 11:25:04
,
所有人可见
,
阅读 156
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N=100010;
typedef long long ll;
int q[N];
int tmp[N];
ll merge_sort_count(int q[],int l,int r){
if(l>=r) return 0;
int mid = l+r >> 1;
ll s;
s = merge_sort_count(q,l,mid)+merge_sort_count(q,mid+1,r);
int k=0;
int i=l,j=mid+1;
while(i<=mid && j<=r){
if(q[i]<=q[j]) tmp[k++]=q[i++];
else {
tmp[k++]=q[j++];
s += 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];
return s;
}
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&q[i]);
cout<<merge_sort_count(q,0,n-1)<<endl;
return 0;
}