归并排序求逆序对数

http://poj.org/problem?id=2299


给出n个数,每次只能交换两个相邻的数,问使得n个数有序最少需要交换多少次。

归并排序的模板,重在理解,小白书p144.


#include <stdio.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <iostream>
#include <limits.h>
#include <algorithm>
#define LL long long
#define _LL __int64
using namespace std;

const int maxn = 500010;
LL cnt;
int n,a[maxn],t[maxn];

void merge_sort(int *a, int x, int y, int *t)
{
	if(y-x > 1)
	{
		int m = x + (y-x)/2;
		int p = x,q = m,i = x;
		merge_sort(a,x,m,t);
		merge_sort(a,m,y,t);
		while(p < m || q < y)
		{
			if(q >= y || (p < m && a[p] <= a[q]))
				t[i++] = a[p++];
			else
			{
				t[i++] = a[q++];
				cnt += m-p;
			}
		}
		for(i = x; i < y; i++)
			a[i] = t[i];
	}
}

int main()
{
	while(~scanf("%d",&n)&&n)
	{
		for(int i = 0; i < n; i++)
			scanf("%d",&a[i]);
		cnt = 0;
		merge_sort(a,0,n,t);
		printf("%lld\n",cnt);
	}
	return 0;
}


http://acm.hdu.edu.cn/showproblem.php?pid=4911


每次只能交换两个相邻的数,最多交换K次,问最后的最少的逆序对数是多少

#include <stdio.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <iostream>
#include <limits.h>
#include <algorithm>
#define LL long long
#define _LL __int64
using namespace std;

const int maxn = 500010;
_LL cnt,k;
int n,a[maxn],t[maxn];

void merge_sort(int *a, int x, int y, int *t)
{
	if(y-x > 1)
	{
		int m = x + (y-x)/2;
		int p = x,q = m,i = x;
		merge_sort(a,x,m,t);
		merge_sort(a,m,y,t);
		while(p < m || q < y)
		{
			if(q >= y || (p < m && a[p] <= a[q]))
				t[i++] = a[p++];
			else
			{
				t[i++] = a[q++];
				cnt += m-p;
			}
		}
		for(i = x; i < y; i++)
			a[i] = t[i];
	}
}

int main()
{
	while(~scanf("%d %I64d",&n,&k))
	{
		for(int i = 0; i < n; i++)
			scanf("%d",&a[i]);
		cnt = 0;
		merge_sort(a,0,n,t);

		if(k >= cnt)
			printf("0\n");
		else
			printf("%I64d\n",cnt-k);
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值