Ultra-QuickSort
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 24722 | Accepted: 8847 |
Description
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
9 1 0 5 4 ,
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.
Ultra-QuickSort produces the output
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
Input
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.
Output
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.
罪过,罪过。。。
在网上找的一个归并排序的模版。。。。。
#include<stdio.h>
#include<string.h>
#include<iostream>
#define maxn 500010
int a[maxn],left[maxn],right[maxn];
long long ans;
void merge(int a[],int p,int q,int r)
{
int n1=q-p+1;
int n2=r-q;
int i,j,k;
for(i=1;i<=n1;i++)
left[i]=a[p+i-1];
for(j=1;j<=n2;j++)
right[j]=a[q+j];
left[n1+1]=1e9; //设置一个哨兵
right[n2+1]=1e9; //同上
i=1;
j=1;
for(k=p;k<=r;k++)
if(left[i]<right[j])
a[k]=left[i++];
else
{
a[k]=right[j++];
ans+=n1-i+1; //计数;
}
}
void mergesort(int a[],int p,int r)
{
if(p<r)
{
int q=(p+r)/2;
mergesort(a,p,q);
mergesort(a,q+1,r);
merge(a,p,q,r); //合并步骤 p<=left<=q q<right<=r;
}
}
int init()
{
int i,n;
scanf("%d",&n);
if (n == 0) return 0;
memset(a,0,sizeof(a));
for(i = 1;i <= n;i++) scanf("%d",&a[i]);
ans = 0;
mergesort(a,1,n);
printf("%lld\n",ans);
return 1;
}
int main()
{
while (init()) ;
return 0;
}