归并排序
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N 500005
int a[N],b[N];
long long count;
void merge(int l,int mid,int r)
{
int i=0,j=l,k=mid+1;
while(j<=mid&&k<=r)
{
if(a[j]>a[k])
{
b[i++]=a[k++];
count+=mid-j+1;
}
else
{
b[i++]=a[j++];
}
}
while(j<=mid)
b[i++]=a[j++];
while(k<=r)
b[i++]=a[k++];
for(j=0;j<i;j++)
a[l+j]=b[j];
}
void mergesort(int l,int r)
{
int mid;
if(l<r)
{
mid=(l+r)/2;
mergesort(l,mid);
mergesort(mid+1,r);
merge(l,mid,r);
}
}
int main()
{
int n,i;
while((scanf("%d",&n)!=EOF)&&n)
{
count=0;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
mergesort(0,n-1);
printf("%I64d\n",count);
}
return 0;
}