E. Ultra-QuickSort
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
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
59105431230
Sample Output
60
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- struct node
- {
- int origin;
- int set;
- }a[500005];
- int n;
- int c[500005],sa[500005];
- int cmp(const void *aa,const void *bb)
- {
- node *a=(node *)aa;
- node *b=(node *)bb;
- return a->origin-b->origin;
- }
- int lowbit(int x)
- {
- return x&(-x);
- }
- void update(int i,int x)
- {
- while(i<=n)
- {
- c[i]+=x;
- i+=lowbit(i);
- }
- }
- int getsum(int i)
- {
- int sum=0;
- while(i>0)
- {
- sum+=c[i];
- i-=lowbit(i);
- }
- return sum;
- }
- int main()
- {
- int i;
- long long ss;
- while(scanf("%d",&n)&&n!=0)
- {
- ss=0;
- for(i=1;i<=n;i++)
- {
- scanf("%d",&a[i].origin);
- a[i].set=i;
- }
- qsort(a+1,n,sizeof(a[0]),cmp);
- for(i=1;i<=n;i++) //没错,就是这里,完全没有必要的一个语句,不知道那个大神加了上去, 然后同学们就疯狂的参考,转载
- sa[a[i].set]=i;
- memset(c,0,sizeof(c));
- for(i=1;i<=n;i++)
- {
- update(sa[i],1);
- ss=ss+i-getsum(sa[i]);
- }
- printf("%lld\n",ss);
- }
- }