【BZOJ1001】狼抓兔子
【BZOJ1001】狼抓兔子
题面
题解
懒得平面图转对偶图了,直接最小割板子加优化。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <climits>
using namespace std;
inline int gi() {
register int data = 0, w = 1;
register char ch = 0;
while (!isdigit(ch) && ch != '-') ch = getchar();
if (ch == '-') w = -1, ch = getchar();
while (isdigit(ch)) data = 10 * data + ch - '0', ch = getchar();
return w * data;
}
const int MAX_N = 1005;
struct Graph { int to, cap, rev, next; } e[MAX_N * MAX_N * 6]; int fir[MAX_N * MAX_N], e_cnt = 0;
void clearGraph() { memset(fir, -1, sizeof(fir)); e_cnt = 0; }
void Add_Edge(int u, int v, int c) {
e[e_cnt] = (Graph){v, c, e_cnt + 1, fir[u]}; fir[u] = e_cnt++;
e[e_cnt] = (Graph){u, c, e_cnt - 1, fir[v]}; fir[v] = e_cnt++;
}
queue<int> que;
int V, iter[MAX_N * MAX_N], level[MAX_N * MAX_N];
void bfs(int s) {
fill(&level[1], &level[V + 1], -1);
while (!que.empty()) que.pop();
level[s] = 0; que.push(s);
while (!que.empty()) {
int x = que.front(); que.pop();
for (int i = fir[x]; ~i; i = e[i].next) {
int v = e[i].to;
if (level[v] < 0 && e[i].cap > 0) {
level[v] = level[x] + 1;
que.push(v);
}
}
}
}
int dfs(int x, int t, int f) {
if (x == t) return f;
for (int &i = iter[x]; ~i; i = e[i].next) {
int v = e[i].to;
if (e[i].cap > 0 && level[v] > level[x]) {
int d = dfs(v, t, min(f, e[i].cap));
if (d) {
e[i].cap -= d;
e[e[i].rev].cap += d;
return d;
}
}
}
level[x] = -1;
return 0;
}
int max_flow(int s, int t) {
int flow = 0;
for (;;) {
for (int i = 1; i <= V; i++) iter[i] = fir[i];
bfs(s);
if (level[t] == -1) return flow;
int f = 0;
while (f = dfs(s, t, INT_MAX)) flow += f;
}
}
int N, M, S, T, id[MAX_N][MAX_N], cnt;
int main () {
#ifndef ONLINE_JUDGE
freopen("cpp.in", "r", stdin);
#endif
clearGraph();
N = gi(), M = gi();
int cnt = 0; S = 1;
for (int i = 1; i <= N; i++)
for (int j = 1; j <= M; j++)
id[i][j] = ++cnt;
T = id[N][M]; V = cnt;
for (int i = 1; i <= N; i++)
for (int j = 1; j < M; j++)
Add_Edge(id[i][j], id[i][j + 1], gi());
for (int i = 1; i < N; i++)
for (int j = 1; j <= M; j++)
Add_Edge(id[i][j], id[i + 1][j], gi());
for (int i = 1; i < N; i++)
for (int j = 1; j < M; j++)
Add_Edge(id[i][j], id[i + 1][j + 1], gi());
printf("%d\n", max_flow(S, T));
return 0;
}