参考自:点击打开链接
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
解题思路:
这个题就不能像之前那样直接求逆序对了,一定会超时(o(n^2))。
采用归并算法的原理,复杂度降到o(nlog(n)),具体分析可百度,cnt=mid-i+1。
#include<stdio.h> # define N 500050 int a[N]; long long int cnt; void merge(int l,int mid,int r) { int i=l,j=mid+1,k=l;// int tmp[N]; while(i<=mid&&j<=r) { if(a[i]<=a[j]) { tmp[k++]=a[i++]; } else { tmp[k++]=a[j++]; cnt+=mid-i+1;//求逆序对 } } while(i<=mid) tmp[k++]=a[i++]; while(j<=r) tmp[k++]=a[j++]; for(i=l;i<=r;i++)// a[i]=tmp[i]; } void merge_sort(int l,int r) { if(l<r) { int mid=(l+r)/2; merge_sort(l,mid); merge_sort(mid+1,r); merge(l,mid,r); } } int main() { int n; while(scanf("%d",&n)!=EOF&&n) { int i; for(i=1;i<=n;i++) scanf("%d",&a[i]); cnt=0; merge_sort(1,n); printf("%lld\n",cnt); } return 0; }