您的位置:首页 > 产品设计 > UI/UE

POJ 2299 Ultra-QuickSort

2012-07-17 20:18 239 查看
思路:

利用归并排序求逆序数

#include<stdio.h>
#define MAX 500002
int s[MAX];
int t[MAX];
__int64 count;
void mergeArray(int first,int mid,int last)
{
int i,j,k=0;
i=first;j=mid+1;
while(i<=mid&&j<=last)
{
if(s[i]>s[j])
{
t[k++]=s[j++];
count+=mid-i+1;
}
else t[k++]=s[i++];

}
while(i<=mid) t[k++]=s[i++];
while(j<=last) t[k++]=s[j++];
for(i=0;i<k;i++)
s[first+i]=t[i];
}
void mergeSort(int first,int last)
{
int mid;
if(first<last)
{
mid=(first+last)/2;
mergeSort(first,mid);
mergeSort(mid+1,last);
mergeArray(first,mid,last);
}
}
int main()
{
int n,i;
while(scanf("%d",&n)!=EOF&&n!=0)
{
count=0;
for(i=0;i<n;i++)
scanf("%d",&s[i]);
mergeSort(0,n-1);
printf("%I64d\n",count);

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: