# POJ 2299 Ultra-QuickSort C语言版

POJ题解 3331浏览

Description

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

5
9
1
0
5
4
3
1
2
3
0

Sample Output

6
0

Slyar:题目本质就是求逆序对了，简单介绍一下。逆序对是指在序列{a0,a1,a2…an}中，若ai<aj(i>j)，则(ai,aj)上一对逆序对。而逆序数顾名思义就是序列中逆序对的个数。例如： 1 2 3是顺序，则逆序数是0；1 3 2中(2,3)满足逆序对的条件，所以逆序数只有1； 3 2 1中(1,2)(1,3)(2,3)满足逆序对，所以逆序是3。由定义不能想象，序列n的逆序数范围在[0,n*(n-1)/2]，其中顺序时逆序数为 0，完全逆序时逆序数是n*(n-1)/2。

PS.归并算法基本思路

```#include
#include

#define MAX 500001

int n, a[MAX], t[MAX];
__int64 sum;

/* 归并 */
void Merge(int l, int m, int r)
{
/* p指向输出区间 */
int p = 0;
/* i、j指向2个输入区间 */
int i = l, j = m + 1;
/* 2个输入区间都不为空时 */
while(i <= m && j <= r)
{
/* 取关键字小的记录转移至输出区间 */
if (a[i] > a[j])
{
t[p++] = a[j++];
/* a[i]后面的数字对于a[j]都是逆序的 */
sum += m - i + 1;
}
else
{
t[p++] = a[i++];
}
}
/* 将非空的输入区间转移至输出区间 */
while(i <= m) t[p++] = a[i++];
while(j <= r) t[p++] = a[j++];
/* 归并完成后将结果复制到原输入数组 */
for (i = 0; i < p; i++)
{
a[l + i] = t[i];
}
}

/* 归并排序 */
void MergeSort(int l, int r)
{
int m;
if (l < r)
{
/* 将长度为n的输入序列分成两个长度为n/2的子序列 */
m = (l + r) / 2;
/* 对两个子序列分别进行归并排序 */
MergeSort(l, m);
MergeSort(m + 1, r);
/* 将2个排好的子序列合并成最终有序序列 */
Merge(l, m, r);
}
}

int main()
{
int i;
while(1)
{
scanf("%d", &n);
if (n == 0) break;
sum=0;
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
MergeSort(0, n - 1);
printf("%I64d\n", sum);
}
//system("pause");
return 0;
}
```

### 网友最新评论 (4)

1. 确实不错啊，瞻仰
涛声依旧7年前 (2013-08-05)回复
2. merge sort 写的很清晰，逆序对分析也很到位！ 学习了！Thanks!
hua10年前 (2011-06-21)回复
3. 把你的POJ上的每一篇报告仔细研读了一下，收获很多，真是非常感谢你~~~呵呵
流觞10年前 (2011-04-18)回复
4. 真是太好了,谢谢！
Frank11年前 (2009-10-18)回复