bzoj 1143 [CTSC2008]祭祀river 网络流

题面

题目传送门

解法

\(x\)与它所有能到达的点\(y\)连边,然后这依然是一个DAG

然后就变成一条边不能选取两端的问题了

直接用n-二分图最大匹配即可

代码

#include <bits/stdc++.h>
#define N 110
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
	x = 0; int f = 1; char c = getchar();
	while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
	while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
struct Edge {
	int next, num, c;
} e[N * N * N];
int s, t, cnt, l[N * 2], cur[N * 2], a[N][N];
void add(int x, int y, int c) {
	e[++cnt] = (Edge) {e[x].next, y, c};
	e[x].next = cnt;
}
void Add(int x, int y, int c) {
	add(x, y, c), add(y, x, 0);
}
bool bfs(int s) {
	for (int i = 1; i <= t; i++) l[i] = -1;
	queue <int> q; q.push(s);
	while (!q.empty()) {
		int x = q.front(); q.pop();
		for (int p = e[x].next; p; p = e[p].next) {
			int k = e[p].num, c = e[p].c;
			if (c && l[k] == -1)
				l[k] = l[x] + 1, q.push(k);
		}
	}
	return l[t] != -1;
}
int dfs(int x, int lim) {
	if (x == t) return lim;
	int used = 0;
	for (int p = cur[x]; p; p = e[p].next) {
		int k = e[p].num, c = e[p].c;
		if (c && l[k] == l[x] + 1) {
			int w = dfs(k, min(c, lim - used));
			e[p].c -= w, e[p ^ 1].c += w; used += w;
			if (e[p].c) cur[x] = p;
			if (used == lim) return lim;
		}
	}
	if (!used) l[x] = -1; return used;
}
int dinic() {
	int ret = 0;
	while (bfs(s)) {
		for (int i = 0; i <= t; i++) cur[i] = e[i].next;
		ret += dfs(s, INT_MAX);
	}
	return ret;
}
int main() {
	int n, m; read(n), read(m);
	for (int i = 1; i <= m; i++) {
		int x, y; read(x), read(y);
		a[x][y] = 1;
	}
	for (int k = 1; k <= n; k++)
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= n; j++)
				if (i != k && i != j && j != k)
					a[i][j] |= a[i][k] & a[k][j];
	s = 0, t = cnt = 2 * n + 1;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
			if (a[i][j] && i != j) Add(i, j + n, 1);
	for (int i = 1; i <= n; i++)
		Add(s, i, 1), Add(i + n, t, 1);
	cout << n - dinic() << "\n";
	return 0;
}

posted @ 2018-08-14 18:23  谜のNOIP  阅读(58)  评论(0编辑  收藏