[BZOJ 1412][ZJOI 2009] 狼和羊的故事

题目大意

有一个 (n times m) 的网格,每一个格子上是羊、狼、空地中的一种,羊和狼可以走上空地。现要在格子边上建立围栏,求把狼羊分离的最少围栏数。

(1 leqslant n, ; m leqslant 100)

题目链接

BZOJ 1412

CodeVS 2351

题解

最小割。

从源点向羊/狼连一条容量无限的边,从狼/羊向汇点连一条容量无限的边。考虑相邻的两格,若是一狼一羊,则连一条容量为 (1) 的边(分割狼羊),若至少有一方为空地,也连一条容量为 (1) 的边(狼羊会走上空地)。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

#include
#include
#include
const int MAXN = 105;
struct ;
struct Node {
Edge *e, *curr;
int level;
} N[MAXN * MAXN];
struct {
Node *u, *v;
Edge *next, *rev;
int cap, flow;
Edge(Node *u, Node *v, int cap) : u(u), v(v), cap(cap), flow(0), next(u->e) {}
};
void addEdge(int u, int v, int cap) {
N[u].e = new Edge(&N[u], &N[v], cap);
N[v].e = new Edge(&N[v], &N[u], 0);
N[u].e->rev = N[v].e;
N[v].e->rev = N[u].e;
}
struct Dinic {
bool makeLevelGraph(Node *s, Node *t, int n) {
for (int i = 0; i < n; i++) N[i].level = 0;
std::queue q;
q.push(s);
s->level = 1;
while (!q.empty()) {
Node *u = q.front();
q.pop();
for (Edge *e = u->e; e; e = e->next) {
大专栏  [BZOJ 1412][ZJOI 2009] 狼和羊的故事 if (e->cap > e->flow && e->v->level == 0) {
e->v->level = u->level + 1;
if (e->v == t) return true;
q.push(e->v);
}
}
}
return false;
}
int findPath(Node *s, Node *t, int limit = INT_MAX) {
if (s == t) return limit;
for (Edge *&e = s->curr; e; e = e->next) {
if (e->cap > e->flow && e->v->level == s->level + 1) {
int flow = findPath(e->v, t, std::min(limit, e->cap - e->flow));
if (flow > 0) {
e->flow += flow;
e->rev->flow -= flow;
return flow;
}
}
}
return 0;
}
int operator()(int s, int t, int n) {
int res = 0;
while (makeLevelGraph(&N[s], &N[t], n)) {
for (int i = 0; i < n; i++) N[i].curr = N[i].e;
int flow;
while ((flow = findPath(&N[s], &N[t])) > 0) res += flow;
}
return res;
}
} dinic;
int n, m;
int getID(int x, int y) {
return (x - 1) * m + y;
}
bool valid(int x, int y) {
return (x > 0) && (y > 0) && (x <= n) && (y <= m);
}
int main() {
scanf("%d %d", &n, &m);
const int s = 0, t = n * m + 1;
static int mat[MAXN][MAXN];
for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) {
scanf("%d", &mat[i][j]);
if (mat[i][j] == 2) addEdge(s, getID(i, j), INT_MAX);
if (mat[i][j] == 1) addEdge(getID(i, j), t, INT_MAX);
}
static int d[4][2] = {
{0, 1},
{0, -1},
{1, 0},
{-1, 0}
};
for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) {
for (int k = 0; k < 4; k++) {
int x = i + d[k][0], y = j + d[k][1];
if (!valid(x, y)) continue;
if (mat[i][j] != mat[x][y] || (mat[i][j] == mat[x][y] && mat[x][y] == 0))
addEdge(getID(i, j), getID(x, y), 1);
}
}
printf("%dn", dinic(s, t, t + 1));
return 0;
}

你可能感兴趣的:([BZOJ 1412][ZJOI 2009] 狼和羊的故事)