「POJ2299」Ultra – QuickSort
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
1 2 3 4 5 6 7 8 9 10 11 |
5 9 1 0 5 4 3 1 2 3 0 |
Sample Output
1 2 |
6 0 |
题解
求逆序对
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
#include<stdio.h> #define N 500001 int n;long long count; int a[N],temp[N]; void sort(int l,int r) { int i,j,k; if(l<r) { k=0; int mid=(r+l)>>1; sort(l,mid);sort(mid+1,r); for(i=l,j=mid+1;i<=mid&&j<=r;) { if(a[i]>a[j])temp[k++]=a[j++]; else { count+=j-mid-1; temp[k++]=a[i++]; } } while(i<=mid) { count+=j-mid-1; temp[k++]=a[i++]; } while(j<=r)temp[k++]=a[j++]; j=l; for(i=0;i<k;i++)a[j++]=temp[i]; } } int main() { while(scanf("%d",&n)&&n!=0) { count =0; for(int i=0;i<n;i++)scanf("%d",&a[i]); sort(0,n-1); printf("%lld\n",count); } return 0; } |
Subscribe