归并排序-递归

来源:互联网 发布:送礼物的淘宝店铺 编辑:程序博客网 时间:2024/05/29 05:52

我们把一个大区间[l,r]分成[l,mid], [mid + 1, r],显然每次我们只要求一个数在左区间,一个数在右区间时的逆序数个数,而不用考虑左区间内和右区间内的逆序数个数,因为合并是自底向上的,左区间和右区间内的逆序数我们已经在他们的子状态中求结果了,所以在自底向上合并时,我们直接累加每一层的逆序数个数就是最后整个区间的逆序数了。


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 
9 1 0 5 4 ,

Ultra-QuickSort produces the output 
0 1 4 5 9 .

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

原创粉丝点击