题目大意:给出一张地图,地图上面的0表示空地,1表示羊,2表示狼,现在要求你建围栏,使得所有的羊都不会被狼攻击,问至少需要建多少个围栏
解题思路:最小割,狼和羊之间的联系就是s–>u….->v–>t(u表示狼,v表示羊),我们要做的就是断开这样的线路,且付出的代价最小,这就是最小割了
狼和源点相连接,容量为INF,羊和汇点相连接,容量为INF(刚开始弄成1了,1的话,就表示1头羊只能被一头狼攻击,这明显是错的),两个格子之间连边,表示围栏,容量为1
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int MAXNODE = 40010;
const int MAXEDGE = 400010;
typedef int Type;
const Type INF = 0x3f3f3f3f;
struct Edge{
int u, v, next;
Type cap, flow;
Edge() {}
Edge(int u, int v, Type cap, Type flow, int next) : u(u), v(v), cap(cap), flow(flow), next(next){}
};
struct Dinic{
int n, m, s, t;
Edge edges[MAXEDGE];
int head[MAXNODE];
int cur[MAXNODE];
bool vis[MAXNODE];
Type d[MAXNODE];
vector<int> cut;
void init(int n) {
this->n = n;
memset(head, -1, sizeof(head));
m = 0;
}
void AddEdge(int u, int v, Type cap) {
edges[m] = Edge(u, v, cap, 0, head[u]);
head[u] = m++;
edges[m] = Edge(v, u, 0, 0, head[v]);
head[v] = m++;
}
bool BFS() {
memset(vis, 0, sizeof(vis));
queue<int> Q;
Q.push(s);
d[s] = 0;
vis[s] = 1;
while (!Q.empty()) {
int u = Q.front(); Q.pop();
for (int i = head[u]; ~i; i = edges[i].next) {
Edge &e = edges[i];
if (!vis[e.v] && e.cap > e.flow) {
vis[e.v] = true;
d[e.v] = d[u] + 1;
Q.push(e.v);
}
}
}
return vis[t];
}
Type DFS(int u, Type a) {
if (u == t || a == 0) return a;
Type flow = 0, f;
for (int &i = cur[u]; i != -1; i = edges[i].next) {
Edge &e = edges[i];
if (d[u] + 1 == d[e.v] && (f = DFS(e.v, min(a, e.cap - e.flow))) > 0) {
e.flow += f;
edges[i ^ 1].flow -= f;
flow += f;
a -= f;
if (a == 0) break;
}
}
return flow;
}
Type Maxflow(int s, int t) {
this->s = s; this->t = t;
Type flow = 0;
while (BFS()) {
for (int i = 0; i < n; i++)
cur[i] = head[i];
flow += DFS(s, INF);
}
return flow;
}
void Mincut() {
cut.clear();
for (int i = 0; i < m; i += 2) {
if (vis[edges[i].u] && !vis[edges[i].v])
cut.push_back(i);
}
}
}dinic;
int n, m, cas = 1;
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
void solve() {
int source = 0, sink = n * m + 1;
dinic.init(sink + 1);
int t;
for (int i = 0; i < n; i++)
for (int j = 1; j <= m; j++) {
scanf("%d", &t);
if (t == 1) dinic.AddEdge(i * m + j, sink, INF);
if (t == 2) dinic.AddEdge(source, i * m + j, INF);
}
int tx, ty;
for (int i = 0; i < n; i++)
for (int j = 1; j <= m; j++)
for (int k = 0; k < 4; k++) {
tx = i + dir[k][0];
ty = j + dir[k][1];
if (tx < 0 || tx >= n || ty < 1 || ty > m) continue;
dinic.AddEdge(i * m + j, tx * m + ty, 1);
}
printf("Case %d:\n%d\n", cas++, dinic.Maxflow(source, sink));
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) solve();
return 0;
}