322 Sort【归并排序】

Sort

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 4
描述
You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need.
For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.
输入
The input consists of T number of test cases.(<0T<1000) Each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n.
输出
For each case, output the minimum times need to sort it in ascending order on a single line.
样例输入
2
3
1 2 3
4
4 3 2 1
样例输出
0
6


用冒泡的排序方法把一个序列排成升序,问最少需要多少次交换......

也就是求序列的逆序数,然后双循环果断超时...也就学了归并排序..刚刚学会,还不是太懂,大概说一下自己的想法......


归并排序:

采用递归(分治)的方法进行,也就是和快排有点像,但是处理不一样,归并的策略是,把每一个序列都分成若干个只包含不多于两个元素的小序列,每个序列内部进行排序,然后回溯到上一级,进行不多于四个的小序列的排序.......依次进行下去,平均时间复杂度是  nlog(n)


这个题需要的是在进行排序的时候直接统计逆序对的个数........


#include<stdio.h>
int x[1005],tp[1005],cnt=0,n;
void merge(int l,int mid,int r)
{
	int i=l,j=mid+1,k=l;
	while(i<=mid&&j<=r)
	{
		if(x[i]<=x[j])
		{
			tp[k++]=x[i++];
		}
		else
		{
			cnt=cnt+mid-i+1;//为防止重复算,每次只需要统计当前序列的逆序数...
			tp[k++]=x[j++];
		}
	}
	while(i<=mid)
	{
		tp[k++]=x[i++];
	}
	while(j<=r)
	{
		tp[k++]=x[j++];
	}
	for(int i=l;i<=r;++i)
	{
		x[i]=tp[i];
	}
}
void sort(int l,int r)
{
	if(l<r)
	{
		int mid=(l+r)>>1;
		sort(l,mid);sort(mid+1,r);//分治
		merge(l,mid,r);//合并
	}
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		for(int i=0;i<n;++i)
		{
			scanf("%d",x+i);
		}
		cnt=0;//清零
		sort(0,n-1);//调用一次
		printf("%d\n",cnt);
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值