Ultra-QuickSort 分类: POJ 排序 2015-08-03 15:39 2人阅读 评论(0) 收藏
Ultra-QuickSort
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 48111 | Accepted: 17549 |
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.
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
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 题意就是求所给序列的逆序数 可以用归并排序求#include <map> #include <list> #include <cmath> #include <queue> #include <stack> #include <string> #include <cstdio> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> #define LL long long #define eps 1e-9 #define PI acos(-1.0) #define INF 0x3f3f3f3f #define CRR fclose(stdin) #define CWW fclose(stdout) #define WW freopen("output.txt","w",stdout) #define RR freopen("input.txt","r",stdin) using namespace std; const int MAX= 500100 ; int a[MAX]; int b[MAX]; int n; LL sum;//开始估计错值,用int 直接爆掉了 void Link_Sqrt(int low,int mid,int Low,int high) { int i=low,j=Low,s=0; while(i<=mid&&j<=high) { while(a[i]<=a[j]&&i<=mid&&j<=high) { b[s++]=a[i++]; } while(a[j]<a[i]&&i<=mid&&j<=high)//当a[i]>a[j]时,因为a[i--mid]与a[mid=1--high]都是有序序列,所以对与a[j]他的逆序数就是mid-i+1 { sum+=(mid-i+1); b[s++]=a[j++]; } } while(i<=mid) { b[s++]=a[i++]; } while(j<=high) { b[s++]=a[j++]; } for(int k=0;k<s;k++) { a[low+k]=b[k]; } } void Sqrt(int low,int high) { int i=low,j=high; if(i>=j) { return ; } int mid=(i+j)/2;//二分 Sqrt(i,mid); Sqrt(mid+1,j); Link_Sqrt(i,mid,mid+1,j);//归并 } int main() { while(scanf("%d",&n),n) { for(int i=0;i<n;i++) { scanf("%d",&a[i]); } sum=0; Sqrt(0,n-1); printf("%lld\n",sum); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。