Ultra-QuickSort
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 50751 | Accepted: 18599 |
Description
![](https://i-blog.csdnimg.cn/blog_migrate/b3530eaa8fa98ef394d3639722240a8c.jpeg)
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<cstdio> #include<iostream> #include<cstring> long long a[500009]={0},b[500009]={0}; using namespace std; long long mergeSort(long long low,long long high); long long merge(long long low,long long mid,long long high); int main() { int n=0; while(scanf("%d",&n)!=EOF&&n>0) { memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); for(int i=0;i<n;i++) scanf("%lld",&a[i]); printf("%lld\n",mergeSort(0,n-1)); } return 0; } long long mergeSort(long long low,long long high) { if(low<high) { long long mid=(low+high)/2; long long k1=mergeSort(low,mid); long long k2=mergeSort(mid+1,high); long long k3=merge(low,mid,high); return k1+k2+k3; } else return 0; } long long merge(long long low,long long mid,long long high) { long long t=mid+1; long long s=low; long long k=low; long long sum=0; while(s<=mid&&t<=high) { if(a[s]<a[t]) { b[k]=a[s++]; } else { sum+=mid-low+1-(s-low); b[k]=a[t++]; } k++; } while(s<=mid) b[k++]=a[s++]; while(t<=high) b[k++]=a[t++]; for (int i=low;i<=high;++i) { a[i]=b[i]; } return sum; }