HDU_3338
至于具体怎么建图在其他博客里可以找得到(网络流的题解实在写起来比较费劲,所以这次就偷懒一下了……),不过值得一提的是,不必像大多数博客说的那样每个空白格子既要向管辖行的run连条边又要向管辖列的run连条边,实际上只要把对应的管辖行的run和对应的管辖列的run连条边就可以了,这条边就代表了这个空白格子,流过的流量就是这个格子要填的数。
#include<stdio.h> #include<string.h> #include<algorithm> #define MAXD 20010 #define MAXN 110 #define MAXM 60010 #define INF 0x3f3f3f3f int N, M, first[MAXD], e, next[MAXM], v[MAXM], flow[MAXM], id[MAXN][MAXN]; int S, T, d[MAXD], work[MAXD], q[MAXD]; int R, C, g[MAXN][MAXN], right[MAXN][MAXN], down[MAXN][MAXN], rid[MAXN][MAXN], cid[MAXN][MAXN]; char b[10]; void init() { int i, j, k; memset(g, 0, sizeof(g)); for(i = 1; i <= N; i ++) for(j = 1; j <= M; j ++) { scanf("%s", b); if(b[0] == '.') g[i][j] = 1; else if(b[3] != 'X') { b[3] = '\0'; g[i][j] = down[i][j] = right[i][j] = -1; if(b[0] != 'X') sscanf(b, "%d", &down[i][j]); if(b[4] != 'X') sscanf(b + 4, "%d", &right[i][j]); } } R = C = 0; memset(rid, 0, sizeof(rid)); memset(cid, 0, sizeof(cid)); for(i = 1; i <= N; i ++) for(j = 1; j <= M; j ++) if(g[i][j] == 1) { if(!rid[i][j]) { ++ R; for(k = j; k <= M && g[i][k] == 1; k ++) rid[i][k] = R; } right[i][j - 1] -= k - j; if(!cid[i][j]) { ++ C; for(k = i; k <= N && g[k][j] == 1; k ++) cid[k][j] = C; } down[i - 1][j] -= k - i; } } void add(int x, int y, int z) { v[e] = y, flow[e] = z; next[e] = first[x], first[x] = e ++; } void build() { int i, j, k, p; S = 0, T = R + C + 1; memset(first, -1, sizeof(first[0]) * (T + 1)), e = 0; for(i = 1; i <= N; i ++) for(j = 1; j <= M; j ++) if(g[i][j] == 1) { id[i][j] = e; add(rid[i][j], R + cid[i][j], 8), add(R + cid[i][j], rid[i][j], 0); } for(i = 1; i <= N; i ++) for(j = 1; j <= M; j ++) if(g[i][j] == -1) { if(right[i][j] != -1) p = rid[i][j + 1], add(S, p, right[i][j]), add(p, S, 0); if(down[i][j] != -1) p = cid[i + 1][j], add(R + p, T, down[i][j]), add(T, R + p, 0); } } int bfs() { int i, j, rear = 0; memset(d, -1, sizeof(d[0]) * (T + 1)); d[S] = 0, q[rear ++] = S; for(i = 0; i < rear; i ++) for(j = first[q[i]]; j != -1; j = next[j]) if(flow[j] && d[v[j]] == -1) { d[v[j]] = d[q[i]] + 1, q[rear ++] = v[j]; if(v[j] == T) return 1; } return 0; } int dfs(int cur, int a) { if(cur == T) return a; for(int &i = work[cur]; i != -1; i = next[i]) if(flow[i] && d[v[i]] == d[cur] + 1) if(int t = dfs(v[i], std::min(a, flow[i]))) { flow[i] -= t, flow[i ^ 1] += t; return t; } return 0; } int dinic() { int ans = 0, t; while(bfs()) { memcpy(work, first, sizeof(first[0]) * (T + 1)); while(t = dfs(S, INF)) ans += t; } return ans; } void solve() { int i, j; build(); dinic(); for(i = 1; i <= N; i ++) { for(j = 1; j <= M; j ++) { if(j != 1) printf(" "); if(g[i][j] == 1) printf("%d", flow[id[i][j] ^ 1] + 1); else printf("_"); } printf("\n"); } } int main() { while(scanf("%d%d", &N, &M) == 2) { init(); solve(); } return 0; }