Description
In this problem, you have to analyze a particle 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 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 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
The optimized Bubble sorting, from small to large, is to find the BREAK when there is no exchange, and ask how many Bubble Sorting can be done.
Idea: because the number on the left is greater than the number on the right, we need to find the number of inverse number pairs. Merge Sorting can be used to solve the problem.
LANGUAGE: C
CODE:
[Html]
# Include <iostream>
# Include <cstdlib>
# Include <cstdio>
Using namespace std;
Int a [500005], c [500005];
Long cnt;
Void mergesort (int left, int right)
{
Int mid, I, j, tmp;
If (right> left + 1)
{
Mid = (left + right)/2;
Mergesort (left, mid );
Mergesort (mid, right );
Tmp = left;
For (I = left, j = mid; I <mid & j <right ;)
{
If (a [I]> a [j])
{
C [tmp ++] = a [j ++];
Cnt + = mid-I;
}
Else c [tmp ++] = a [I ++];
}
If (j <right) for (; j <right; ++ j) c [tmp ++] = a [j];
Else for (; I <mid; ++ I) c [tmp ++] = a [I];
For (I = left; I <right; ++ I) a [I] = c [I];
}
}
Int main ()
{
// Freopen ("in.txt", "r", stdin );
Int n;
While (cin> n, n)
{
Cnt = 0;
For (int I = 1; I <= n; I ++)
Cin> a [I];
Mergesort (1, n + 1 );
Cout <cnt <endl;
}
Return 0;
}
Author: ultimater