Ultra-QuickSort
Time Limit: 7000MS |
|
Memory Limit: 65536K |
Total Submissions: 48121 |
|
Accepted: 17553 |
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.
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.
Sample Input
5
9
1
0
5
4
3
1
2
3
0
Sample Output
6
0
Source
题意:
给出n个数,要求求出按照冒泡排序法需要多少次才能把这n个数按从小到大的顺序排列。
思路:
需要多少次才能按从小到大的顺序排列,可以转化成求其逆序数(这个线代学过),但是n<=500000,逆序数可能会超过int ,所以结果要用long long ,否则wrong answer.求其逆序数可以用归并排序,按照分治三步:
1.划分问题:吧序列分成元素个数尽量相等的两半。
2.递归求解:把元素分别排列。
3.把两个有序表合并成一个。
中间过程需要引入一个辅助空间T[n].
每一次累加cnt+=m-p;即是答案。
代码:
#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;
}