bzoj 3144 [Hnoi2013]切糕

Input

100%的数据满足P,Q,R≤40，0≤D≤R，且给出的所有的不和谐值不超过1000。

2 2 2
1
6 1
6 1
2 6
2 6

6

题解

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cmath>
#define N 45*45*45+10
using namespace std;
const int inf = 0x3f3f3f3f;
struct flows {
struct node {
int to, next, flow;
} e[300010];
int tot, st[N], dis[N], cur[N];
void init() {
tot = -1, memset(e, -1, sizeof e),
memset(st, -1, sizeof st);
}
void add(int x, int y, int z) {
e[++tot].to = y;
e[tot].flow = z;
e[tot].next = st[x];
st[x] = tot;
}
void add_edge(int x, int y, int z) {
//      printf("add%d %d %d\n", x, y, z);
}
queue <int> que;
int bfs(int S, int T) {
memcpy(cur, st, sizeof st);
memset(dis, 0, sizeof dis);
while (!que.empty()) que.pop();
que.push(S);
dis[S] = 1;
while(!que.empty()) {
int now = que.front();
que.pop();
for (int i = st[now]; ~i; i = e[i].next)
if (e[i].flow && !dis[e[i].to]) {
dis[e[i].to] = dis[now] + 1;
if (e[i].to == T) return 1;
que.push(e[i].to);
}
}
return 0;
}
int finds(int now, int T, int flow) {
if (now == T)
return flow;
int f;
for (int i = cur[now]; ~i; i = e[i].next) {
cur[now] = i;
if (e[i].flow && dis[e[i].to] == dis[now] + 1 &&
(f = finds(e[i].to, T, min(flow, e[i].flow)))) {
e[i].flow -= f;
e[i^1].flow += f;
return f;
}
}
return 0;
}
int dinic(int S, int T) {
int flow = 0, x;
while(bfs(S, T)) {
while(x = finds(S, T, inf)) {
flow += x;
}
}
return flow;
}
}flow;
int a, b, c, d, v[41][41][41], ans;
int ge(int x, int y, int z) { return x * b * c + y * c + z; }
int dir[5][2] = { {0, 1}, {0, -1}, {1, 0}, {-1, 0} };
main() {
scanf("%d%d%d%d", &b, &c, &a, &d);
int S = 0, T = N - 1;
flow.init();
for (int i = 1; i <= a; ++i)
for (int j = 1; j <= b; ++j)
for (int k = 1; k <= c; ++k)
scanf("%d", &v[i][j][k]);
for (int i = 1; i <= b; ++i)
for (int j = 1; j <= c; ++j)
flow.add_edge(S, ge(0, i, j), inf);
for (int i = 1; i <= a; ++i)
for (int j = 1; j <= b; ++j)
for (int k = 1; k <= c; ++k)
flow.add_edge(ge(i - 1, j, k), ge(i, j, k), v[i][j][k]);
for (int i = 1; i <= b; ++i)
for (int j = 1; j <= c; ++j)
flow.add_edge(ge(a, i, j), T, inf);
for (int i = d + 1; i <= a; ++i)
for (int j = 1; j <= b; ++j)
for (int k = 1; k <= c; ++k)
for (int l = 0; l <= 4; ++l)
if (j + dir[l][0] >= 1 && j + dir[l][0] <= b && k + dir[l][1] >= 1 && k + dir[l][1] <= c)
flow.add_edge(ge(i, j, k), ge(i - d, j + dir[l][0], k + dir[l][1]), inf);
printf("%d\n", flow.dinic(S, T));
}