文章标题

来源:互联网 发布:057188157858是淘宝网 编辑:程序博客网 时间:2024/05/21 07:14

poj 2299 Ultra-QuickSort

Time Limit: 7000MS Memory Limit: 65536K
Total Submissions: 53779 Accepted: 19767
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
解题思路:利用分治的方法来排序,这样是所有排序的算法里边的最省时的一个,已经是世界都公认的,排完序的过程就可以计算最后的counts的值;
我的代码就在下边,不过很抱歉,这个头文件不知道在这个markdown编译器里边怎么排版,所以头文件有点怪怪的,抱歉啊,具体的题解在代码里边有,读者可以看看,笔者就不多说了。
Waterloo local 2005.02.05#include<iostream>#include<cstdio>#include<cstring>
using namespace std;
__int64 counts=0;//代表counts是long long 型数据
int a[500005],A[500005],n;
void Sort(int from,int mid,int to)
{
int i=from,j=mid+1,k=from;
while(i<=mid&&j<=to)
if(a[i]<=a[j]){A[k++]=a[i++];}
else {A[k++]=a[j++];counts+=j-k;}
while(i<=mid)A[k++]=a[i++];//后边三步其实在这道题都不用写,因为并没有让给a数组排序
while(j<=to)A[k++]=a[j++];
for(int i=from;i<=to;i++)
a[i]=A[i];
}
void Merge_Sort(int from,int to)
{
if(from>=to)return;
int mid=(from+to)>>1;//用位移符号比除号速度更快,更省时
Merge_Sort(from,mid);//分治左边
Merge_Sort(mid+1,to);//分治右边
Sort(from,mid,to);//一定要记得合起来;
}
int main()
{
while(~scanf("%d",&n)&&n)
{
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
counts=0;
Merge_Sort(0,n-1);
printf("%I64d\n",counts);//只有64位才不会wa!!!!!
}
}

0 0
原创粉丝点击