HDU 2255 — 奔小康賺大錢 KM入門題

原題:http://acm.hdu.edu.cn/showproblem.php?pid=2255


#include<stdio.h>
#include<string.h>
#include<algorithm>
#define inf 1e9

using namespace std;
const int maxn = 310;
int nx, ny;		//nx、ny分別表示X集和Y集的頂點數; 
int match[maxn];
int lx[maxn], ly[maxn], slack[maxn], w[maxn][maxn];		//lx、ly分別爲X集和Y集的頂標; 
bool visx[maxn], visy[maxn];

bool dfs(int x)
{
	visx[x] = true;
	for(int y = 1;y<=ny;y++)
	{
		if(visy[y])	continue;
		
		int t = lx[x]+ly[y]-w[x][y];
		if(t == 0)
		{
			visy[y] = true;
			if(match[y] == 0 || dfs(match[y]))
			{
				match[y] = x;
				return true;
			}
		}
		else if(slack[y]>t)
		slack[y] = t;
	}
	return false;
}

int KM()
{
	memset(ly, 0, sizeof ly);
	memset(match, 0, sizeof match);
	for(int i = 1;i<=nx;i++)	//將lx初始化爲與它關聯的邊中權值最大的; 
	{
		lx[i] = -inf;
		for(int j = 1;j<=ny;j++)
		lx[i] = max(lx[i], w[i][j]);
	}
	for(int x = 1;x<=nx;x++)
	{
		for(int y = 1;y<=ny;y++)
		slack[y] = inf;
		while(1)
		{
			memset(visx, false, sizeof visx);
			memset(visy, false, sizeof visy);
			if(dfs(x))	//如果成功,則表示找到了增廣軌,該點增廣完成,就可以尋找下一個點的增廣軌; 
			break;		//如果失敗,則需要改變一些點的標號,增加可行邊; 
			int d = inf;
			for(int i = 1;i<=ny;i++)
			{
				if(!visy[i])
				d = min(d, slack[i]);
			}
			for(int i = 1;i<=nx;i++)
			{
				if(visx[i])
				lx[i]-=d;
			}
			for(int i = 1;i<=ny;i++)
			{
				if(visy[i])
				ly[i]+=d;
				else
				slack[i]-=d;
			}
		}
	}
	int res = 0;
	for(int i = 1;i<=ny;i++)
	{
		if(match[i])
		res+=w[match[i]][i];
	}
	return res;
}

int main()
{
	int n;
	while(scanf("%d", &n)!=EOF)
	{
		nx = ny = n;
		for(int i = 1;i<=n;i++)
			for(int j = 1;j<=n;j++)
				scanf("%d", &w[i][j]);
		int ans = KM();
		printf("%d\n", ans);
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章