首页 > 代码库 > poj 2299 Ultra-QuickSort

poj 2299 Ultra-QuickSort

Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536K
Total Submissions: 39436 Accepted: 14214

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


题意:求序列的逆序数。

分析:用归并排序求解。

(具体算法:http://blog.csdn.net/fyxz1314/article/details/37604005

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define max 510000
#define M 100000000

int a[max];
int L[max],R[max];
__int64 sum;

void merge(int l,int m,int r)
{
	int n1,n2;
	int i,j,k;
	n1=m-l+1;   // l 到 m 的元素个数
	n2=r-m;     // m+1到 r 的元素个数
	
	for(i=1;i<=n1;i++)    //把l到m的左边元素复制到L数组里面
		L[i]=a[l+i-1];
	for(i=1;i<=n2;i++)    //把m+1到r的右边元素复制到R数组里面
		R[i]=a[m+i];
	
	L[n1+1] = M;      // 底部存放“哨兵”,避免比较式判空。 M要比较大。
	R[n2+1] = M;
	
	i=1;j=1;
	for(k=l;k<=r;k++)   //  每次把两堆中最小的元素复制到数组A中,这样合并成有序的序列
	{
	  if(L[i]<=R[j])
	  {
		  a[k]=L[i];
		  i++;
	  }
	  else
	  {
	   a[k]=R[j];
	   j++;
	   sum+=(n1-i+1);
	  }
	}
	
}

void mergesort(int l,int r)
{
	int m;
	if(l<r)
	{
		m=(l+r)/2;
		mergesort(l,m);
		mergesort(m+1,r);
		merge(l,m,r);
	}
}

int main ()
{
	int n,i,j;
	while (~scanf("%d",&n)&&n!=0)
	{   
		sum=0;
		for(i=0;i<n;i++)
			scanf("%d",&a[i]);
		mergesort(0,n-1);
		printf("%I64d\n",sum);
	}
	return 0;
}