hdu 1533 Going Home(zkw费用流)

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


#define N 1002
#define M 500020
#define inf 0x3f3f3f3f
#define eps 1e-8
#define inf 0x3f3f3f3f



int n;
int m;
char str[N][N];
int x[N], y[N], xx[N], yy[N];
int nx, ny;
struct zkw {
	int C, D;
	int s, t;
	int fst[N], nxt[M], vv[M], cap[M], flow[M], cost[M], e;
	bool vis[N];
	void init() {
		memset(fst, -1, sizeof fst);
		e = 0;
		C = D = 0;
	}
	void add(int u, int v, int f, int c) {
		vv[e] = v, nxt[e] = fst[u], cost[e] = c, cap[e] = f, flow[e] = 0, fst[u] = e++;
		vv[e] = u, nxt[e] = fst[v], cost[e] = -c, cap[e] = flow[e] = 0, fst[v] = e++;
	}
	int aug(int u, int f) {
		if(u == t) {
			C += D * f;
			return f;
		}
		vis[u] = 1;
		int tmp = f;
		for(int i = fst[u]; ~i; i = nxt[i]) {
			int v = vv[i];
			if(cap[i] > flow[i] && cost[i] == 0 && !vis[v]) {
				int d = aug(v, tmp < cap[i] - flow[i]? tmp: cap[i] - flow[i]);
				flow[i] += d;
				flow[i^1] -= d;
				tmp -= d;
				if(!tmp) return f;
			}
		}
		return f - tmp;
	}
	bool modLabel() {
		int d = inf;
		for(int i = 0; i <= t; ++i) if(vis[i]) {
			for(int j = fst[i]; ~j; j = nxt[j]) {
				int v = vv[j];
				if(cap[j] > flow[j] && !vis[v] && cost[j] < d) d = cost[j];
			}
		}
		if(d == inf) return 0;
		for(int i = 0; i <= t; ++i) {
			if(vis[i]) {
				for(int j = fst[i]; ~j; j = nxt[j]) {
					int v = vv[j];
					cost[j] -= d;
					cost[j^1] += d;
				}
			}
		}
		D += d;
		return 1;
	}
	int gao(int s, int t) {
		this -> s = s, this -> t = t;
		do do memset(vis, 0, sizeof vis);
		while(aug(s, inf)); while(modLabel());
		return C;
	}
}go;





int main() {
	while(scanf("%d%d", &n, &m) != EOF && n) {
		nx = ny = 0;
		for(int i = 1; i <= n; ++i) {
			scanf("%s", str[i] + 1);
			for(int j = 1; j <= m; ++j) {
				if(str[i][j] == 'm') {
					nx++;
					x[nx] = i;
					y[nx] = j;
				}
				if(str[i][j] == 'H') {
					ny++;
					xx[ny] = i;
					yy[ny] = j;
				}
			}
		}
		int s = 0, t = nx + ny + 1;
		go.init();
		for(int i = 1; i <= nx; ++i) {
			for(int j = 1; j <= ny; ++j) {
				int d = abs(x[i] - xx[j]);
				d += abs(y[i] - yy[j]);
				go.add(i, j + nx, 1, d);
			}
		}
		for(int i = 1; i <= nx; ++i) go.add(s, i, 1, 0);
		for(int i = 1; i <= ny; ++i) go.add(i + nx, t, 1, 0);
		printf("%d\n", go.gao(s, t));
	}
	
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值