【KM模板】HDU 2255 奔小康赚大钱


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


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
#define rep(i,l,r) for(int i=(l),_=(r);i<=_;i++)
#define per(i,r,l) for(int i=(r),_=(l);i>=_;i--)
#define MS(arr,x) memset(arr,x,sizeof(arr))
#define INE(i,u) for(int i=head[u];~i;i=e[i].next)
#define LL long long
inline const int read()
{int r=0,k=1;char c=getchar();for(;c<'0'||c>'9';c=getchar())if(c=='-')k=-1;
for(;c>='0'&&c<='9';c=getchar())r=r*10+c-'0';return k*r;}

const int inf=0x3f3f3f3f;
int n;
int W[333][333],X[333],Y[333],pre[333],d;
bool S[333],T[333];

void MAX(int &a,int b){if(a<b)a=b;}
void MIN(int &a,int b){if(a>b)a=b;}
bool dfs(int i)
{
	S[i]=1;
	rep(j,1,n)
	{
		if(X[i]+Y[j]==W[i][j] && !T[j])
		{
			T[j]=1;
			if(pre[j]<0 || dfs(pre[j]))
			{
				pre[j]=i;
				return 1;
			}
		}
		else if(X[i]+Y[j]>W[i][j])
		    MIN(d,X[i]+Y[j]-W[i][j]);
	}
	return 0;
}
int KM()
{
	rep(i,1,n)
	{
		X[i]=Y[i]=0; pre[i]=-1;
		rep(j,1,n) MAX(X[i],W[i][j]);
	}
	rep(i,1,n) for(;;)
	{
		rep(j,1,n) S[j]=T[j]=0;
		d=inf;
		if(dfs(i)) break;
		rep(j,1,n)
		{
			if(S[j]) X[j]-=d;
			if(T[j]) Y[j]+=d;
		}
	}
	int res=0;
	rep(i,1,n) res+=X[i]+Y[i];
	return res;
}

void input()
{
    rep(i,1,n) rep(j,1,n) W[i][j]=read();
}
void solve()
{
	printf("%d\n",KM());
}

int main()
{
    //freopen("_.in","r",stdin); freopen("_.out","w",stdout);
    while(~scanf("%d",&n))
    input(),solve();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值