图论 二分图 hdu1533 KM最大匹配

题意:求h和m对应,匹配相互 曼哈顿距离最小值

题解: h与m相对应,i为h,j为m,g[i][j]为第i个h与第j个m的曼哈顿距离 最小,边权,为负来跑

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

const int MAXNODE = 505;

typedef int Type;
const Type INF = 0x3f3f3f3f;

struct KM {
	int n;
	Type g[MAXNODE][MAXNODE];
	Type Lx[MAXNODE], Ly[MAXNODE], slack[MAXNODE];
	int left[MAXNODE], right[MAXNODE];
	bool S[MAXNODE], T[MAXNODE];

	void init(int n) {
		this->n = n;
	}

	void add_Edge(int u, int v, Type val) {
		g[u][v] = val;
	}

	bool dfs(int i) {
		S[i] = true;
		for (int j = 0; j < n; j++) {
			if (T[j]) continue;
			Type tmp = Lx[i] + Ly[j] - g[i][j];
			if (!tmp) {
				T[j] = true;
				if (left[j] == -1 || dfs(left[j])) {
					left[j] = i;
					right[i] = j;
					return true;
				}
			} else slack[j] = min(slack[j], tmp);
		}
		return false;
	}

	void update() {
		Type a = INF;
		for (int i = 0; i < n; i++)
			if (!T[i]) a = min(a, slack[i]);
		for (int i = 0; i < n; i++)
			if (S[i]) Lx[i] -= a;
		for (int i = 0; i < n; i++)
			if (T[i]) Ly[i] += a;
	}

	Type km() {
		memset(left, -1, sizeof(left));
		memset(right, -1, sizeof(right));
		memset(Ly, 0, sizeof(Ly));
		for (int i = 0; i < n; i++) {
			Lx[i] = -INF;
			for (int j = 0; j < n; j++)
				Lx[i] = max(Lx[i], g[i][j]);
		}
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) slack[j] = INF;
			while (1) {
				memset(S, false, sizeof(S));
				memset(T, false, sizeof(T));
				if (dfs(i)) break;
				else update();
			}
		}
		Type ans = 0;
		for (int i = 0; i < n; i++)
			ans += g[i][right[i]];
		return ans;
	}
} km;
const int N=105;
int n,m;
char str[N];

struct point{
	int x,y;
	point(){}
	point(int x,int y){
		this->x=x;
		this->y=y;
	}
}hp[N],mp[N];
int hn,mn;
int dis(point a,point b){
	return abs(a.x-b.x)+abs(a.y-b.y);
}
int main() 
{
	while (~scanf("%d%d", &n,&m)&& n||m){
		hn=mn=0;
		for(int i=0;i<n;i++){
			scanf("%s",str);
			for(int j=0;j<m;j++){
				if(str[j]=='H') hp[hn++]=point(i,j);
				if(str[j]=='m') mp[mn++]=point(i,j);
			}
		}
		km.n=hn;
		for(int i=0;i<hn;i++)
			for(int j=0;j<mn;j++)
				km.g[i][j]= -dis(hp[i],mp[j]);
		printf("%d\n",-km.km());
		
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值