Description
In this problem, you has to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping, 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 what many swap operations Ultra-quicksort needs to perform in order to sort a given input sequenc E.
Input
The input contains several test cases. Every test case begins with a line this contains a single integer n < 500,000-the length of the input sequence. Each of 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 is processed.
Output
For every input sequence, your program prints a single line containing an integer number OP, the minimum number of swap op Erations necessary to sort the given input sequence.
Sample Input
59105431230
Sample Output
60
Test instructions: The number of times a minimum interchange of adjacent elements is required to change the sequence to an ascending sequence;
Idea: Merge sort to seek reverse order number;
AC Code:
#include <iostream>#include<cstdio>#include<algorithm>#defineN 500010typedefLong Longll;using namespacestd;ll a[n];ll ans=0; ll Tmp[n];voidMerge_ (intLintMintR) { intCnt=0; inti,j; for(i=l,j=m+1; i<=m&&j<=R;) {if(A[i]<=a[j]) {Tmp[++cnt]=a[i]; i++;} Else{tmp[++CNT]=A[J]; J + +; Ans+ = (m-i+1); } } while(i<=m) {Tmp[++cnt]=a[i]; i++;} while(J<=R) {Tmp[++cnt]=a[j]; J + +;} for(i=l,j=1; i<=r&&j<=cnt;i++,j++) a[i]=tmp[j];}voidMerge_sort (intLintR) { if(L==R)return; if(l<R) { intM= (l+r) >>1; Merge_sort (L,M); Merge_sort (M+1, R); Merge_ (L,M,R); }}intMain () {intN; while(SCANF ("%d", &n)!=eof&&N) { for(intI=1; i<=n;i++) cin>>A[i]; Ans=0; Merge_sort (1, N); cout<<ans<<Endl; } return 0;}
Don't you know how to get a picture?
[Merge Sort] Ultra-quicksort