POJ - 2299 Ultra-QuickSort

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的序列,只允许交换相邻的两个元素,问至少需要交换多少次才能排列成一个递增的序列,

解题思路: 直接冒泡的话坑定会超时,归并排序来做,我们一般用归并排序来求逆序数,其实这道题可以转换为求逆序数

一个乱序序列的 逆序数 = 在只允许相邻两个元素交换的条件下,得到有序序列的交换次数

例如例子的

9 1 0 5 4

由于要把它排列为上升序列,上升序列的有序就是  后面的元素比前面的元素大

而对于序列9 1 0 5 4

9后面却有4个比9小的元素,因此9的逆序数为4

1后面只有1个比1小的元素0,因此1的逆序数为1

0后面不存在比他小的元素,因此0的逆序数为0

5后面存在1个比他小的元素4, 因此5的逆序数为1

4是序列的最后元素,逆序数为0

因此序列9 1 0 5 4的逆序数 t=4+1+0+1+0 = 6  ,恰恰就是冒泡的交换次数

这样就简单的多了

逆序数参考连接:https://blog.csdn.net/qq_40707370/article/details/85221743

AC代码:

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=1e6;
int a[maxn];
long long ans;
void merge(int a[],int left,int mid,int right,int temp[])
{
	int i=left,j=mid+1,k=0;
	while(i<=mid&&j<=right)
	{
		if(a[i]<a[j])
			temp[k++]=a[i++];
		else
		{
			ans+=mid-i+1;
			temp[k++]=a[j++];
		}
	}
	while(i<=mid)
		temp[k++]=a[i++];
	while(j<=right)
		temp[k++]=a[j++];
	for(i=0;i<k;i++)
		a[left+i]=temp[i];
}
int mergesort(int a[],int left,int right,int temp[])
{
	if(left<right)
	{
		int mid=(left+right)/2;
		mergesort(a,left,mid,temp);
		mergesort(a,mid+1,right,temp);
		merge(a,left,mid,right,temp);
	}
}
void sort(int a[],int n)
{
	int temp[n];
	mergesort(a,0,n-1,temp);
}
int main()
{
	int n;
	while(scanf("%d",&n),n)
	{
		ans=0;
		for(int i=0;i<n;i++)
			scanf("%d",&a[i]);
		sort(a,n);
		printf("%lld\n",ans);
	} 
	return 0;
}
 

猜你喜欢

转载自blog.csdn.net/qq_40707370/article/details/85802098