POJ 2229 Ultra-QuickSort 归并排序求逆序数
2016-03-16 19:05
483 查看
题目描述:
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
题目分析:
这道题乍一看是一个求冒泡排序的交换次数,其实看到数据大小很明显是不能用冒泡排序来做的。这道题其实要求我们掌握归并排序以及其运用归并排序来求逆序数的方法。其中归并排序的具体思想可以看一个大牛的博客:
http://blog.csdn.net/morewindows/article/details/6678165/
代码如下:
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <algorithm> const int MAXN=500005; const int INF = 0x3f3f3f3f; using namespace std; long long ans; int leftdata[MAXN/2+1], rightdata[MAXN/2+1]; void merge(int *a,int start,int mid,int end) { int n1=mid-start+1; int n2=end-mid; int c1=0,c2=0; for(int i=0; i<n1; i++) leftdata[i]=a[start+i]; for(int i=0; i<n2; i++) rightdata[i]=a[mid+1+i]; leftdata[n1]=rightdata[n2]=INF; for(int t=start; t<=end; t++) { if (leftdata[c1]<=rightdata[c2]) { a[t]=leftdata[c1]; c1++; } else { a[t]=rightdata[c2]; c2++; ans+=n1-c1; } } return; } void mergesort(int *a,int start,int end) { int mid; if (start<end) { mid=(start+end)/2; mergesort(a,start,mid); mergesort(a,mid+1,end); merge(a,start,mid,end); } return; } int main() { int a[MAXN]; int n; while(~scanf("%d",&n) && n) { ans=0; for(int i=0; i<n; i++) { scanf("%d",&a[i]); } mergesort(a,0,n-1); printf("%lld\n",ans); } return 0; }
相关文章推荐
- Number Sequence (HDU_1711) KMP
- build模式小例子
- [ShareSDK] QuickIntegrater.jar文件各种打不开
- UITextField - 解决键盘遮住View & 密文设定 & 实例
- 今天遇到 Request failed: method not allowed (405)。 错误,特此在网上翻了翻
- 187. Repeated DNA Sequences LeetCode
- use vs require in Perl5
- UI初级 TextField
- POJ 2299 Ultra-QuickSort
- UI初级 Label
- 使用Fragment 实现动态UI
- Elasticsearch 评分score计算中的Boost 和 queryNorm
- UI入门 纯代码 第一节 UIWindow, UIView
- Starting MySQL. ERROR! The server quit without updating PID file
- 详解 UIView 的 Tint Color 属性
- iOS UITextField不显示光标
- 关于Android studio项目sdk1\build-tools\23.0.1\zipalign.exe'' finished with non-zero exit value 1问题
- android UI设计时须要注意遵循的设计原则
- pt-query-digest怎么分析慢查询日志分析数据
- requirejs笔记