AcWing 788. 逆序对的数量
原题链接
简单
#include<iostream>
using namespace std;
const int N=1e5+10;
int n,s[N],tmp[N];
long long merge_sort(int s[],int l,int r)
{
if(l>=r)return 0;
int mid=(l+r)>>1;
long long res=merge_sort(s,l,mid)+merge_sort(s,mid+1,r);
int i=l,j=mid+1,k=0;
while(i<=mid&&j<=r)
if(s[i]<=s[j])tmp[k++]=s[i++];
else res+=mid-i+1,tmp[k++]=s[j++];
if(i<=mid)while(i<=mid)tmp[k++]=s[i++];
if(j<=r)while(j<=r)tmp[k++]=s[j++];
for(int i=l,j=0;i<=r;i++,j++)s[i]=tmp[j];
return res;
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)scanf("%d",&s[i]);
cout<<merge_sort(s,0,n-1)<<endl;
return 0;
}