洛谷 P3227 [HNOI2013]切糕(最小割)

题解

Dinic求最小割

题目其实就是求最小的代价使得每个纵轴被分成两部分

最小割!!!

我们把每个点抽象成一条边,一个纵轴就是一条\(S-T\)的路径

但是题目要求\(|f(x,y)-f(x’,y’)| ≤D\)

不能直接跑最小割

考虑如何限制

首先,\(|f(x,y)-f(x’,y’)| ≤D\)是相互的

所以只要考虑 \(f(x,y)-f(x',y')\leq D\)

限制想一想看代码就明白了

代码就很简洁了

Code

#include<bits/stdc++.h>

#define LL long long
#define RG register

using namespace std;
template<class T> inline void read(T &x) {
    x = 0; RG char c = getchar(); bool f = 0;
    while (c != '-' && (c < '0' || c > '9')) c = getchar(); if (c == '-') c = getchar(), f = 1;
    while (c >= '0' && c <= '9') x = x*10+c-48, c = getchar();
    x = f ? -x : x;
    return ;
}
template<class T> inline void write(T x) {
    if (!x) {putchar(48);return ;}
    if (x < 0) x = -x, putchar('-');
    int len = -1, z[20]; while (x > 0) z[++len] = x%10, x /= 10;
    for (RG int i = len; i >= 0; i--) putchar(z[i]+48);return ;
}

const int N = 80000, inf = 2147483647;

struct node {
	int to, nxt, w;
}g[2000000];
int last[N], gl = 1;

void add(int x, int y, int z) {
	g[++gl] = (node) {y, last[x], z};
	last[x] = gl;
	g[++gl] = (node) {x, last[y], 0};
	last[y] = gl;
}

queue<int> q;
int dep[N], s, t, cur[N];

bool bfs() {
	memset(dep, 0, sizeof(dep));
	dep[s] = 1;
	q.push(s);
	while (!q.empty()) {
		int u = q.front(); q.pop();
		for (int i = last[u]; i; i = g[i].nxt) {
			int v = g[i].to;
			if (!dep[v] && g[i].w) {
				dep[v] = dep[u]+1;
				q.push(v);
			}
		}
	}
	return dep[t] == 0 ? 0 : 1;
}

int dfs(int u, int d) {
	if (u == t) return d;
	for (int &i = cur[u]; i; i = g[i].nxt) {
		int v = g[i].to;
		if (dep[v] == dep[u]+1 && g[i].w) {
			int di = dfs(v, min(d, g[i].w));
			if (di) {
				g[i].w -= di;
				g[i^1].w += di;
				return di;
			}
		}
	}
	return 0;
}

int Dinic() {
	int ans = 0;
	while (bfs()) {
		for (int i = 1; i <= t; i++) cur[i] = last[i];
		while (int d = dfs(s, inf)) ans += d;
	}
	return ans;
}

int a[50][50][50], id[50][50][50];

int fx[] = {0, 1, -1, 0};
int fy[] = {1, 0, 0, -1};

int main() {
	int p, q, r, d, tot = 0;
	read(p), read(q), read(r), read(d);
	for (int i = 1; i <= r; i++)
		for (int j = 1; j <= p; j++)
			for (int k = 1; k <= q; k++)
				read(a[i][j][k]), id[i][j][k] = ++tot;
	for (int j = 1; j <= p; j++)
		for (int k = 1; k <= q; k++)
			id[r+1][j][k] = ++tot;			
	s = tot+1, t = s+1;
	for (int i = 1; i <= p; i++)
		for (int j = 1; j <= q; j++)
			add(s, id[1][i][j], inf), add(id[r+1][i][j], t, inf);
	
	for (int k = 1; k <= r; k++)
		for (int i = 1; i <= p; i++)
			for (int j = 1; j <= q; j++)
				add(id[k][i][j], id[k+1][i][j], a[k][i][j]);
	
	for (int k = d+1; k <= r+1; k++)
		for (int i = 1; i <= p; i++)
			for (int j = 1; j <= q; j++) {
				for (int z = 0; z < 4; z++) {
					int x = i + fx[z], y = j + fy[z];
					if (x < 1 || y < 1 || x > p || y > q) continue;
					add(id[k][i][j], id[k-d][x][y], inf);
				}
			}
	
	printf("%d\n", Dinic());
	return 0;
}


posted @ 2019-01-19 23:24  zzy2005  阅读(113)  评论(0编辑  收藏  举报