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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
| /**************************************************************
Problem: 1412
User: MagHSK
Language: C++
Result: Accepted
Time:100 ms
Memory:3316 kb
****************************************************************/
#include <iostream>
#include <cstdio>
using namespace std;
const int INF = 1<<30;
typedef long long LL;
int getint() {
int r = 0, k = 1; char c = getchar();
for (; '0' > c || c > '9'; c = getchar()) if (c == '-') k = -1;
for (; '0' <= c && c <= '9'; c = getchar()) r = r * 10 - '0' + c;
return r * k;
}
int n, m, id[105][105];
const int dx[4] = {-1,0,1,0}, dy[4] = {0,1,0,-1};
const int maxedge = 100005;
const int maxnode = 50005;
struct MaxFlowSolver {
int S, T;
struct edge_type {
int to, next, r;
} edge[maxedge];
int h[maxnode], cur[maxnode], dis[maxnode], cnte, L, R;
void init() {
cnte = 1;
for (int i = 0; i < maxnode; ++i) h[i] = 0;
S = T = 0;
L = maxnode;
R = 0;
}
void range(int l, int r) { L = l; R = r; }
void ins(int u, int v, int w) {
edge[++cnte].to = v;
edge[cnte].next = h[u];
edge[cnte].r = w;
h[u] = cnte;
edge[++cnte].to = u;
edge[cnte].next = h[v];
edge[cnte].r = 0;
h[v] = cnte;
}
int q[maxnode];
bool BFS() {
int head = 0, tail = 1;
q[0] = S;
for (int i = L; i <= R; ++i) dis[i] = -1;
dis[S] = 0;
int now;
while (head < tail) {
now = q[head++];
for (int i = h[now]; i; i = edge[i].next) {
if (dis[edge[i].to] == -1 && edge[i].r) {
dis[edge[i].to] = dis[now] + 1;
q[tail++] = edge[i].to;
}
}
}
return dis[T] != -1;
}
int DFS(int now, int a) {
if (now == T || a == 0) return a;
int f, ret = 0;
for (int &i = cur[now]; i; i = edge[i].next) {
if (dis[edge[i].to] != dis[now] + 1) continue;
if (f = DFS(edge[i].to, min(a, edge[i].r))) {
a -= f;
ret += f;
edge[i].r -= f;
edge[i^1].r += f;
if (!a) break;
}
}
if (!ret) dis[now] = -1;
return ret;
}
int Dinic(int start, int end) {
S = start; T = end;
int ret = 0;
while (BFS()) {
for (int i = L; i <= R; ++i) cur[i] = h[i];
ret += DFS(S, INF);
}
return ret;
}
} G;
int land[105][105];
int main() {
G.init();
n = getint(); m = getint();
int sum = 0;
int S = 1, T = 2;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j)
id[i][j] = T++;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j)
land[i][j] = getint();
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) {
if (land[i][j] == 1) G.ins(S, id[i][j], INF);
if (land[i][j] == 2) { G.ins(id[i][j], T, INF); continue; }
for (int k = 0; k < 4; ++k) {
int tx = i + dx[k], ty = j + dy[k];
if (1<=tx&&tx<=n&&1<=ty&&ty<=m)
if(land[i][j]!=1||land[tx][ty]!=1)
G.ins(id[i][j], id[tx][ty], 1);
}
}
G.range(S, T);
int ans = G.Dinic(S, T);
printf("%d", ans);
return 0;
}
|