In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence
Ultra-QuickSort produces the output
0 1 4 5 9 .Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.
For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.
5 9 1 0 5 4 3 1 2 3 0
6 0
这道题用到了归并排序问题,解题代码如下:
#include<stdio.h>
__int64 k=0;
int a[500005],b1[500005];
void merge(int *b,int low,int m,int high)
{
int i=low,j=m+1,p=0;
while(i<=m&&j<=high)
{
if(b[i]<=b[j])
{
b1[p++]=b[i++];
}
else
{
b1[p++]=b[j++];
k+=(m-i+1);
}
}
while(i<=m)
{
b1[p++]=b[i++];
}
while(j<=high)
{
b1[p++]=b[j++];
}
for(p=0,i=low;i<=high;p++,i++)
{
b[i]=b1[p];
}
}
void mergesort(int *b,int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(b,low,mid);
mergesort(b,mid+1,high);
merge(b,low,mid,high);
}
}
int main()
{
int i,n;
while(scanf("%d",&n)!=EOF)
{
k=0;
if(n==0)
break;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
mergesort(a,0,n-1);
printf("%I64d\n",k);
}
return 0;
}