Ultra-quicksort
| Time Limit: 7000MS |
|
Memory Limit: 65536K |
| Total Submissions: 52306 |
|
Accepted: 19194 |
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
Source
Waterloo Local 2005.02.05Test Instructions: Given n number, only the adjacent two elements can be exchanged, at least a few times, to become an increment sequence. The following:The number of reverse order of the sequence is clearly required ... For example:59 1 0) 5 4we'll sort it out:0 1 4) 5 9the initial drop is 1 at each location.1 1 1) 1 1then, start the traversal from the original sequence. first up to 9, we took it out in the right order,that is 5. then count the number of 1 before position 5. 1 1 1) 1 1———— > 4 x ans+=4then put the number 5th position at 0. 1 1 1) 1 0continue the operation can ... This tree-like array can be maintained ... note the long long and the original sequence after the order to go to the heavy ...
1#include <bits/stdc++.h>2 using namespacestd;3 #defineMAXN 5000104 #defineLL Long Long5 intN,BIT[MAXN],A[MAXN],AA[MAXN];6 intRead ()7 {8 ints=0, fh=1;CharCh=GetChar ();9 while(ch<'0'|| Ch>'9'){if(ch=='-') fh=-1; ch=GetChar ();}Ten while(ch>='0'&&ch<='9') {s=s*Ten+ (ch-'0'); ch=GetChar ();} One returns*fh; A } - intLowbit (intO) {returno& (-o);} - voidUpdate (intOintO1) the { - while(o<=N) - { -bit[o]+=O1; +o+=lowbit (o); - } + } A intSum (into) at { - intsum=0; - while(o>0) - { -sum+=Bit[o]; -o-=lowbit (o); in } - returnsum; to } + intMain () - { the intTot,i,wz; * LL ans; $ while(1)Panax Notoginseng { -N=read ();if(n==0) Break; the for(i=1; i<=n;i++) {a[i]=read (); aa[i]=a[i];} +memset (BIT,0,sizeof(BIT)); ASort (A +1, a+n+1); theTot=unique (A +1, a+n+1)-(A +1); + for(i=1; i<=tot;i++) Update (i,1); -ans=0; $ for(i=1; i<=n;i++) $ { -Wz=lower_bound (A +1, a+tot+1, Aa[i])-A; -ans+= (LL) Sum (wz-1); the if(bit[wz]!=0) Update (wz,-1); - }Wuyiprintf"%lld\n", ans); the } - fclose (stdin); Wu fclose (stdout); - return 0; About}View Code
|