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

归并排序求逆序对数

时间:2014-08-06 10:38:41      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:归并排序   逆序对数   

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;
}



归并排序求逆序对数,布布扣,bubuko.com

归并排序求逆序对数

标签:归并排序   逆序对数   

原文地址:http://blog.csdn.net/u013081425/article/details/38395413

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