Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P1935 [国家集训队]圈地计划

P1935 [国家集训队]圈地计划

经典的建图模型。

查看代码
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <climits>
#define inf INT_MAX
using namespace std;
const int N = 1e4 + 10, M = 5e5 + 10;
int n, m, st, ed, tot, ans, d[N], cur[N];
int idx = -1, hd[N], nxt[M], edg[M], wt[M];
int dx[4] = { 0, 1, -1, 0 }, dy[4] = { 1, 0, 0, -1 };
void add(int a, int b, int c)
{
nxt[++idx] = hd[a];
hd[a] = idx;
edg[idx] = b;
wt[idx] = c;
}
int num(int x, int y)
{
return (x - 1) * m + y;
}
bool inside(int x, int y)
{
return x > 0 && y > 0 && x <= n && y <= m;
}
void init()
{
memset(hd, -1, sizeof hd);
cin >> n >> m;
st = 0;
tot = ed = n * m + 1;
for (int i = 1, a; i <= n; i++)
for (int j = 1; j <= m; j++)
{
cin >> a;
ans += a;
int p = num(i, j);
if (i + j & 1)
{
add(st, p, a);
add(p, st, 0);
}
else
{
add(p, ed, a);
add(ed, p, 0);
}
}
for (int i = 1, a; i <= n; i++)
for (int j = 1; j <= m; j++)
{
cin >> a;
ans += a;
int p = num(i, j);
if (i + j & 1)
{
add(p, ed, a);
add(ed, p, 0);
}
else
{
add(st, p, a);
add(p, st, 0);
}
}
for (int i = 1, a; i <= n; i++)
for (int j = 1; j <= m; j++)
{
cin >> a;
int p = num(i, j);
for (int k = 0; k < 4; k++)
{
int nx = i + dx[k], ny = j + dy[k];
int q = num(nx, ny);
if (!inside(nx, ny))
continue;
ans += a << 1;
add(st, ++tot, a);
add(tot, st, 0);
add(tot, p, inf);
add(p, tot, 0);
add(tot, q, inf);
add(q, tot, 0);
add(++tot, ed, a);
add(ed, tot, 0);
add(p, tot, inf);
add(tot, p, 0);
add(q, tot, inf);
add(tot, q, 0);
}
}
}
bool bfs()
{
memset(d, -1, sizeof d);
d[st] = 0;
cur[st] = hd[st];
queue <int> q;
q.push(st);
while (!q.empty())
{
int t = q.front();
q.pop();
for (int i = hd[t]; ~i; i = nxt[i])
if (d[edg[i]] == -1 && wt[i])
{
cur[edg[i]] = hd[edg[i]];
d[edg[i]] = d[t] + 1;
if (edg[i] == ed)
return true;
q.push(edg[i]);
}
}
return false;
}
int exploit(int x, int limit)
{
if (x == ed)
return limit;
int res = 0;
for (int i = cur[x]; ~i && res < limit; i = nxt[i])
{
cur[x] = i;
if (d[edg[i]] == d[x] + 1 && wt[i])
{
int t = exploit(edg[i], min(wt[i], limit - res));
if (!t)
d[edg[i]] = -1;
wt[i] -= t;
wt[i ^ 1] += t;
res += t;
}
}
return res;
}
int dinic()
{
int res = 0, flow;
while (bfs())
while (flow = exploit(st, inf))
res += flow;
return res;
}
int main()
{
init();
cout << ans - dinic();
return 0;
}