zoj3286-------------------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 numberop, 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


在归并排序的分步骤里面添加一个计数步骤即可~数组元素和计数的count的类型都用long long,蛋疼 = =




代码:

#include <iostream>
#include <climits>
using namespace std;

long long merge(long long A[],int p,int q,int r)
{
	int n1=q-p+1;
	int n2=r-q;
	long long count=0;
	long long *L=new long long[n1+2];
	long long *R=new long long[n2+2];
	for(int i=1;i<=n1;i++)
		L[i]=A[p+i-1];	
	for(int i=1;i<=n2;i++)
		R[i]=A[q+i];
	L[n1+1]=INT_MAX;
	R[n2+1]=INT_MAX;
	int i,j; 
	i=1;
	j=1;
	for(int k=p;k<=r;k++)
	{
		if(L[i]<=R[j])
		{
			count=count+j-1;
			A[k]=L[i];
			i++;	
		}
		else
		{
			A[k]=R[j];
			j++;	
		}	
	}
	delete[]L;
	delete[]R;
	return count;
}


long long merge_sort(long long A[],int p,int r)
{
	long long count=0;
	if(p<r)
	{
		int q=(p+r)/2;
		count=count+merge_sort(A,p,q);	
		count=count+merge_sort(A,q+1,r);
		count=count+merge(A,p,q,r);
	}
	return count;
}

int main()
{
	long long N;
	while(cin>>N&&N!=0)
	{
		long long A[N];
		long long count;
		for(int i=1;i<=N;i++)
			cin>>A[i];
		count=merge_sort(A,1,N);
		cout<<count<<endl;
	}
	return 0;	
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值