HDU2255 KM完备最大匹配

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define For(i,j,k) for (i=j;i<=k;i++)
using namespace std;

const int dmax=1010,INF=1000000000;
int n,m,d[dmax],lx[dmax],ly[dmax],w[dmax][dmax],slack[dmax];
bool px[dmax],py[dmax];

bool dfs(int x){
	int i,j;
	px[x]=1;
	For(i,1,n){
		if (py[i]) continue;
		int t=lx[x]+ly[i]-w[x][i];
		if (t==0){
			py[i]=1;
			if (!d[i] || dfs(d[i])){
				d[i]=x;
				return 1;
			}
		}
		if (t<slack[i])
			slack[i]=t;
	}
	return 0;
}

int main(){
	int i,j,k;
while (scanf("%d",&n)!=EOF){
	memset(d,0,sizeof(d));
	for (i=1;i<=n;i++) slack[i]=INF;
	For(i,1,n)
		For(j,1,n)
			scanf("%d",&w[i][j]);
	int max=0;
	For(i,1,n){
		max=0;
		For(j,1,n)
			if (w[i][j]>max)
				max=w[i][j];
		lx[i]=max;
	}
	For(i,1,n){
		For(j,1,n) slack[j]=INF;
		while (1){
			memset(px,0,sizeof(px));
			memset(py,0,sizeof(py));
			if (dfs(i))
				break;
			int dx=INF;
			For(j,1,n)
				if (!py[j] && slack[j]<dx)
					dx=slack[j];
			For(j,1,n)
				if (px[j])
					lx[j]-=dx;
			For(j,1,n)
				if (py[j])
					ly[j]+=dx;
				else slack[j]-=dx;
		}
	}
	int ans=0;
	For(i,1,n)
		if (d[i])
			ans+=w[d[i]][i];
	printf("%d\n",ans);
}
	return 0;
}

你可能感兴趣的:(HDU2255 KM完备最大匹配)