Dinic 求助
查看原帖
Dinic 求助
148851
wtyqwq楼主2020/5/4 20:35

只过了 33 个点,最大流模板刚过。

#include <stdio.h>
#define M 51005
#define N (1 << 10)
#define INF 0x3F3F3F3F
int head[N], ver[M << 1], nex[M << 1], edge[M << 1];
int d[N], n, k, m, tot = 1, S, T;
int flow, res, Head, Tail, q[N];
int min(int a, int b) { return a < b ? a : b; }
void add(int x, int y, int k) {
	ver[++tot] = y;
	edge[tot] = k;
	nex[tot] = head[x];
	head[x] = tot;
}
bool Bfs(int s, int t) {
	for (int i = 1; i <= n; ++i) d[i] = 0;
	Head = 1, q[Tail = 1] = s, d[s] = 1;
	while (Head <= Tail) {
		int x = q[Head++];
		for (int i = head[x], y; i; i = nex[i]) {
			if (edge[i] && !d[y = ver[i]]) {
				q[++Tail] = y, d[y] = d[x] + 1;
				if (y == t)
					return true;
			}
		}
	}
	return false;
}
int Dinic(int x, int flow) {
	if (x == T)
		return flow;
	int Rest = flow, k;
	for (int i = head[x], y = ver[i]; i && Rest; i = nex[i]) {
		if (edge[i] && d[y = ver[i]] == d[x] + 1) {
			if (!(k = Dinic(y, min(Rest, edge[i]))))
				d[y] = 0;
			edge[i] -= k, edge[i ^ 1] += k, Rest -= k;
		}
	}
	return flow - Rest;
}
int main() {
	S = N - 2, T = N - 1;
	scanf("%d %d %d", &n, &k, &m);
	for (int i = 1; i <= m; ++i) {
		int x, y;
		scanf("%d %d", &x, &y);
		add(x, y + n, 1);
		add(y + n, x, 0);
	}
	for (int i = 1; i <= n; ++i) {
		add(S, i, 1);
		add(i, S, 0);
	}
	for (int i = 1; i <= k; ++i) {
		add(i + n, T, 1);
		add(T, i + n, 0);
	}
	while (Bfs(S, T) == true)
		while (flow = Dinic(S, INF)) res += flow;
	printf("%d\n", res);
	return 0;
}
2020/5/4 20:35
加载中...