【BZOJ1066】[SCOI2007]蜥蜴【最大流】

【题目链接】

题里说的距离指的是欧几里得距离。

把每个点拆成两个点,中间连接容量为高度的边。

如果一个点可以到达另一个点,那么一个点的尾连接另一个点的头,容量为inf。

从源点向有蜥蜴的点连边,容量为1。

从可以出地图的点向汇点连边,容量为inf。

/* Footprints In The Blood Soaked Snow */
#include <cstdio>
#include <algorithm>

using namespace std;

const int maxg = 25, maxn = 1005, maxm = 500005, maxq = 10000, inf = 0x3f3f3f3f;

int n, m, d, id[maxg][maxg][2], bg, ed, depth[maxn], q[maxq], head[maxn], cnt, cur[maxn], tot, map[maxg][maxg];

struct _edge {
	int v, w, next;
} g[maxm << 1];

inline void add(int u, int v, int w) {
	g[cnt] = (_edge){v, w, head[u]};
	head[u] = cnt++;
}

inline void insert(int u, int v, int w) {
	add(u, v, w); add(v, u, 0);
}

inline int dis(int x1, int y1, int x2, int y2) {
	return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}

inline void build(int x, int y) {
	int xlb = x - d, xub = x + d, ylb = y - d, yub = y + d;
	if(xlb < 1 || xub > n || ylb < 1 || yub > m) insert(id[x][y][1], ed, inf);
	xlb = max(xlb, 1); xub = min(xub, n); ylb = max(ylb, 1); yub = min(yub, m);
	for(int i = xlb; i <= xub; i++) for(int j = ylb; j <= yub; j++)
		if((i != x || j != y) && map[i][j] && dis(i, j, x, y) <= d * d)
			insert(id[x][y][1], id[i][j][0], inf);
}

inline bool bfs() {
	for(int i = 0; i <= tot; i++) depth[i] = -1;
	int h = 0, t = 0, u, i; depth[q[t++] = bg] = 1;
	while(h != t) for(i = head[u = q[h++]]; ~i; i = g[i].next) if(g[i].w && !~depth[g[i].v]) {
		depth[g[i].v] = depth[u] + 1;
		if(g[i].v == ed) return 1;
		q[t++] = g[i].v;
	}
	return 0;
}

inline int dfs(int x, int flow) {
	if(x == ed) return flow;
	int left = flow;
	for(int i = cur[x]; ~i; i = g[i].next) if(g[i].w && depth[g[i].v] == depth[x] + 1) {
		int tmp = dfs(g[i].v, min(left, g[i].w));
		left -= tmp; g[i].w -= tmp; g[i ^ 1].w += tmp;
		if(g[i].w) cur[x] = i;
		if(!left) return flow;
	}
	if(left == flow) depth[x] = -1;
	return flow - left;
}

char str[maxg];

int main() {
	scanf("%d%d%d", &n, &m, &d);

	tot = bg = 0;
	for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) for(int k = 0; k <= 1; k++)
		id[i][j][k] = ++tot;
	ed = ++tot;

	for(int i = 0; i < maxn; i++) head[i] = -1; cnt = 0;
	for(int i = 1; i <= n; i++) {
		scanf("%s", str + 1);
		for(int j = 1; j <= m; j++) if(str[j] > '0')
			insert(id[i][j][0], id[i][j][1], map[i][j] = str[j] - '0');
	}
	int ans = 0;
	for(int i = 1; i <= n; i++) {
		scanf("%s", str + 1);
		for(int j = 1; j <= m; j++) if(str[j] == 'L')
			insert(bg, id[i][j][0], 1), ans++;
	}
	for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) if(map[i][j])
		build(i, j);
	
	while(bfs()) {
		for(int i = 0; i <= tot; i++) cur[i] = head[i];
		ans -= dfs(bg, inf);
	}

	printf("%d\n", ans);
	return 0;
}


你可能感兴趣的:(网络流,最大流)