逆序对数量
作者:
L_566
,
2024-03-08 14:28:02
,
所有人可见
,
阅读 23
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N=100010;
int a[N],p[N];
int merge_sort(int l,int r)
{
if(l>=r) return 0;
int mid=(l+r)/2;
int res=(merge_sort(l,mid)+merge_sort(mid+1,r));
int i=l,j=mid+1,k=0;
while(i<=mid&&j<=r)
{
if(a[i]<=a[j]) p[k++]=a[i++];
else p[k++]=a[j++],res+=mid-i+1;
}
while(i<=mid) p[k++]=a[i++];
while(j<=r) p[k++]=a[j++];
for(i=l,j=0;i<=r;i++,j++)
a[i]=p[j];
return res;
}
signed main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
cout<<merge_sort(1,n);
return 0;
}