采用二分思想求逆序数对
采用递归的思想,分别向左向右递归二分
#include <stdio.h>
int n;
int a[101000];
int t[101000];
long long ans;
void Merge(int s1,int e1,int s2,int e2)
{
int k=s1;
int p1 = s1;
int p2 = s2;
while (p1<=e1&&p2<=e2)
{
if (a[p1]<=a[p2])
{
t[k++] = a[p1++];
}
else
{
t[k++] = a[p2++];
ans+=e1-p1+1;
}
}
while (p1<=e1)
t[k++] = a[p1++];
while (p2<=e2)
t[k++] = a[p2++];
k--;
while (k>=s1)
{
a[k] = t[k];
k--;
}
}
void MergeSort(int s,int e)
{
int k;
if (s<e)
{
k = (s+e)/2;
MergeSort(s,k);
MergeSort(k+1,e);
Merge(s,k,k+1,e);
}
}
main()
{
int i,j;
ans = 0;
scanf ("%d",&n);
for (i=0; i<n; i++)
scanf ("%d",&a[i]);
MergeSort(0,n-1);
printf ("%lld\n",ans);
}