【HDOJ 2255】奔小康赚大钱(KM算法)

【HDOJ 2255】奔小康赚大钱(KM算法)


奔小康赚大钱

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6051    Accepted Submission(s): 2667


Problem Description
传说在遥远的地方有一个很富裕的村落,有一天,村长决定进行制度改革:又一次分配房子。
这但是一件大事,关系到人民的住房问题啊。

村里共同拥有n间房间,刚好有n家老百姓,考虑到每家都要有房住(假设有老百姓没房子住的话,easy引起不安定因素),每家必须分配到一间房子且仅仅能得到一间房子。
还有一方面,村长和另外的村领导希望得到最大的效益,这样村里的机构才会有钱.因为老百姓都比較富裕,他们都能对每一间房子在他们的经济范围内出一定的价格,比方有3间房子,一家老百姓能够对第一间出10万,对第2间出2万,对第3间出20万.(当然是在他们的经济范围内).如今这个问题就是村领导如何分配房子才干使收入最大.(村民即使有钱购买一间房子但不一定能买到,要看村领导分配的).

 

Input
输入数据包括多组測试用例,每组数据的第一行输入n,表示房子的数量(也是老百姓家的数量),接下来有n行,每行n个数表示第i个村名对第j间房出的价格(n<=300)。
 

Output
请对每组数据输出最大的收入值,每组的输出占一行。

 

Sample Input
2 100 10 15 23
 

Sample Output
123
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:  3360 1083 1281 1533 2426

第一次接触KM算法,在学这个算法前最好先学二分匹配。算是二分图最大匹配的一个演变——带权匹配

网上讲KM的文章也不少,贴两个我学习看的帖子

http://philoscience.iteye.com/blog/1754498

http://blog.sina.com.cn/s/blog_691ce2b701016reh.html

我感觉第一个比較有助于理解,但代码实现是JAVA来写的。第二个能够学学详细写法,当然不是全然固定的,仅供參考。


这题就是个裸题,建个图跑遍KM即可。


代码例如以下:

#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
#include <list>
#include <algorithm>
#include <map>
#include <set>
#define LL long long
#define fread() freopen("in.in","r",stdin)
#define fwrite() freopen("out.out","w",stdout)

using namespace std;
const int INF = 0x3f3f3f3f;
const int msz = 10000;
const double eps = 1e-8;

//存图
int mp[333][333];
//   x顶标   y顶标   
int lx[333],ly[333],link[333],slack[333];
bool visx[333],visy[333];
int n;

bool cal(int x)
{
	visx[x] = 1;
	for(int y = 0; y < n; ++y)
	{
		if(visy[y]) continue;

		int tmp = lx[x]+ly[y]-mp[x][y];
		//边在二分匹配中
		if(tmp == 0)
		{
			visy[y] = 1;
			if(link[y] == -1 || cal(link[y]))
			{
				link[y] = x;
				return 1;
			}
		}
		//边不在二分匹配中
		else slack[y] = min(slack[y],tmp);
	}
	return false;
}

int KM()
{
	memset(ly,0,sizeof(ly));
	memset(link,-1,sizeof(link));

	for(int i = 0; i < n; ++i)
	{
		memset(slack,INF,sizeof(slack));
		while(1)
		{
			memset(visx,0,sizeof(visx));
			memset(visy,0,sizeof(visy));
	
			//xi 得到匹配
			if(cal(i)) break;
	
			int d = INF;
			for(int i = 0; i < n; ++i)
				if(!visy[i]) d = min(d,slack[i]);
	
			//匹配中的x顶标都减去d
			for(int i = 0; i < n; ++i)
				if(visx[i]) lx[i] -= d;
	
			//匹配中的y顶标都加上d
			//否则降低slack
			for(int i = 0; i < n; ++i)
				if(visy[i]) ly[i] += d;
				else slack[i] -= d;
		}
	}

	int ans = 0;
	for(int i = 0; i < n; ++i)
		if(link[i] != -1) ans += mp[link[i]][i];

	return ans;
}

int main()
{
	while(~scanf("%d",&n))
	{
		memset(lx,0,sizeof(lx));
		for(int i = 0; i < n; ++i)
			for(int j = 0; j < n; ++j)
			{
				scanf("%d",&mp[i][j]);
				if(mp[i][j] > lx[i]) lx[i] = mp[i][j];
			}

		printf("%d\n",KM());
	}

	return 0;
}





posted on 2017-07-03 11:11  blfbuaa  阅读(126)  评论(0编辑  收藏  举报