bzoj 1305 [CQOI2009]dance跳舞 二分答案+网络流

题面

题目传送门

解法

这道题建图还是挺妙妙的

显然答案满足单调性,直接二分答案,假设当前答案为\(mid\)

考虑将每一个人拆成2个点,一个表示喜欢,另一个表示不喜欢

\(s\)连向男生喜欢,容量为\(mid\),男生喜欢连向男生不喜欢,容量为\(k\)

女生类似

然后对于男生\(i\)和女生\(j\),如果不互相喜欢,那么连接对应两个表示不喜欢的点,否则连接对应两个表示喜欢的点,容量均为1

这样就可以控制每一个男生最多只会和不超过\(k\)个不喜欢的女生跳舞

然后跑最大流,如果最大流\(f=mid×n\),那么答案合法

代码

#include <bits/stdc++.h>
#define N 210
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 n, k, s, t, cnt, l[N], cur[N], 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;
}
bool check(int mid) {
	s = 0, t = cnt = 4 * n + 1;
	for (int i = 0; i <= t; i++) e[i].next = 0;
	for (int i = 1; i <= n; i++) {
		int i1 = i * 2 - 1, i2 = i1 + 1;
		Add(s, i1, mid), Add(i1, i2, k);
	}
	for (int i = 1; i <= n; i++) {
		int i1 = i * 2 - 1 + 2 * n, i2 = i1 + 1;
		Add(i1, i2, k), Add(i2, t, mid);
	}
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
			if (a[i][j]) Add(i * 2 - 1, j * 2 + 2 * n, 1);
				else Add(i * 2, j * 2 - 1 + 2 * n, 1);
	return dinic() == mid * n;
}
int main() {
	read(n), read(k);
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++) {
			char c = getchar();
			while (!isalpha(c)) c = getchar();
			if (c == 'Y') a[i][j] = 1; else a[i][j] = 0;
		}
	int l = 1, r = n, ans = 0;
	while (l <= r) {
		int mid = (l + r) >> 1;
		if (check(mid)) l = mid + 1, ans = mid;
			else r = mid - 1;
	}
	cout << ans << "\n";
	return 0;
}

posted @ 2018-08-14 22:04  谜のNOIP  阅读(117)  评论(0编辑  收藏  举报