文章标题
2016-07-09 11:26
381 查看
poj 2299 Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536KTotal 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!!!!! } }
相关文章推荐
- 初学ACM - 组合数学基础题目PKU 1833
- POJ ACM 1001
- POJ ACM 1002
- 1611:The Suspects
- POJ1089 区间合并
- POJ 2159 Ancient Cipher
- POJ 2635 The Embarrassed Cryptographe
- POJ 3292 Semi-prime H-numbers
- POJ 2773 HAPPY 2006
- POJ 3090 Visible Lattice Points
- POJ-2409-Let it Bead&&NYOJ-280-LK的项链
- POJ-1695-Magazine Delivery-dp
- POJ1523 SPF dfs
- POJ-1001 求高精度幂-大数乘法系列
- POJ-1003 Hangover
- POJ-1004 Financial Management
- [数论]poj2635__The Embarrassed Cryptographer
- [二分图匹配]poj2446__Chessboard
- POJ1050 最大子矩阵和
- 用单调栈解决最大连续矩形面积问题