hdu 1533 Going Home(zkw费用流)

来源:互联网 发布:数据分析师薪酬待遇 编辑:程序博客网 时间:2024/05/18 21:39
#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 0x3f3f3f3fint 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
原创粉丝点击