码迷,mamicode.com
首页 > 其他好文 > 详细

poj 2299 Ultra-QuickSort

时间:2014-07-11 08:30:42      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   strong   

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

Description

bubuko.com,布布扣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;
}







poj 2299 Ultra-QuickSort,布布扣,bubuko.com

poj 2299 Ultra-QuickSort

标签:des   style   blog   http   color   strong   

原文地址:http://blog.csdn.net/fyxz1314/article/details/37603917

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!