2015 HUAS Summer Trainning #4~A

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

解题思路:由于n的范围太大,O(n^2)的枚举将超时,所以这个问题可以考虑归并排序(归并排序的时间复杂度为O(nlogn)。),因为设置的数字比较大,用int会溢出,用long long来存是最好的。还要注意两个关键条件,首先,只要有一个序列非空,就要继续合并,因此在比较时不能直接比较A[p]和A[q],因为可能其中一个序列非空,从而A[p]和A[q]代表的是一个实际不存在的元素。

程序代码:

 

#include <iostream>
#include<cstdio>
using namespace std;
const int maxn=500005;
int A[maxn],T[maxn];
long long count;

void merge_sort(int x,int y)
{
	if(y-x>1)
	{
		int m=x+(y-x)/2;
		int p=x,q=m,i=x;
		merge_sort(x,m);
		merge_sort(m,y);
		while(p<m||q<y)
		{
			if(q>=y||(p<m&&A[p]<=A[q]))
				T[i++]=A[p++];
			else
			{
				T[i++]=A[q++];
				count+=m-p;
			}
		}
		for(i=x;i<y;i++)
			A[i]=T[i];
	}
}

int main()
{
	int n;
	while(scanf("%d",&n)==1&&n)
	{
		count=0;
		for(int j=0;j<n;j++)
			scanf("%d",&A[j]);
		merge_sort(0,n);
		printf("%I64d
",count);
	}
	return 0;
}

 

原文地址:https://www.cnblogs.com/chenchunhui/p/4702226.html