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
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
- #include"iostream"
- #include"algorithm"
- #include"cstring"
- #include"cstdio"
- using namespace std;
- structxy
- {
- int x,y;
- }a[1000010];
- int c[1005];
- //long long int max;
- int cmp(const xy&a,const xy&b)
- {
- if(a.x!=b.x)
- return a.x<b.x;
- else
- return a.y<b.y;
- }
- int lowbit(int x)
- {
- return x&(-x);
- }
- void updata(int x,int d,int max)
- {
- while(x<=max)
- {
- c[x]+=d;
- x+=lowbit(x);
- }
- }
- long long int getsum(int x)
- {
- long long int res=0;
- while(x>0)
- {
- res+=c[x];
- x-=lowbit(x);
- }
- return res;
- }
- int main()
- {
- int i,t,p=0;
- scanf("%d",&t);
- while(t--)
- {
- int n,m,k,max;
- memset(c,0,sizeof(c));
- max=0;
- scanf("%d%d%d",&n,&m,&k);
- for(i=0;i<k;i++)
- {
- scanf("%d%d",&a[i].x,&a[i].y);
- if(a[i].y>max)
- max=a[i].y;
- }
- sort(a,a+k,cmp);
- long long int sum=0;
- updata(a[0].y,1,max);
- for(i=1;i<k;i++)
- {
- sum+=getsum(max)-getsum(a[i].y);
- updata(a[i].y,1,max);
- }
- printf("Test case %d: %lld\n",++p,sum);
- }
- return 0;
- }