Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 48121 | Accepted: 17553 |
Description
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
Output
Sample Input
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
Source
#include<cstdio>
#include<cstring>
#include<algorithm>
int A[500004],T[500004];
long long cnt;
using namespace std;
void init(int n)
{
for(int i=0;i<n;i++)
scanf("%d",&A[i]);
}
void merge_sort(int *A,int x,int y,int *T)
{
if(y-x>1)
{
int m=x+(y-x)/2;
int p=x,q=m,i=x;
merge_sort(A,x,m,T);
merge_sort(A,m,y,T);
while(p<m||q<y)
{
if(q>=y||(p<m&&A[p]<=A[q])) T[i++]=A[p++];
else
{
T[i++]=A[q++];
cnt+=m-p;
}
} for(i=x;i<y;i++)
A[i]=T[i];
}
}
int main()
{
int n;
while(scanf("%d",&n)&&n)
{
init(n);
cnt=0;
memset(T,0,sizeof(T));
merge_sort(A,0,n,T);//不能把n寫成n-1,否則會答案錯誤
printf("%I64d\n",cnt);
}
return 0;
}