P1129 [ZJOI2007]矩阵游戏

二分图匹配

P1129

这个题还是有一定套路的

将黑色格子所在的行和列连边, 跑一边最大匹配, 如果是完美匹配即可(所有点都是匹配点)

why?

在完美匹配的情况下

假如 列1 -> 行5 , 列4 -> 行1 (->表示匹配)

我们则可以将行5和行1换一下位置, 这样交换 列不会受到影响, 匹配变为列1 -> 行1, 列4 -> 行5

同理, 列2, 列3, 列4也可以通过和别人交换来搞到自己的菜

证毕

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N = 40005;
int h[N], ne[N * 2], to[N * 2];
int tot, T, n;

void add(int x,int y) {
	ne[++tot] = h[x];
	h[x] = tot, to[tot] = y;
}

int read(void) {
	int x = 0;
	char c = getchar();
	while (!isdigit(c)) c = getchar();
	while (isdigit(c)) {
		x = (x << 3) + (x << 1) + c - '0';
		c = getchar();
	}
	return x;
}

int tim, vis[N], match[N];

int dfs(int x) {
	for (int i = h[x]; i; i = ne[i]) {
		int y = to[i];
		if (vis[y] == tim) continue;
		vis[y] = tim;
		if (!match[y] || dfs(match[y])) {
			match[y] = x; return 1;
		}
	}
	return 0;
}

void pre(void) {
	memset(h, 0, sizeof(h));
	memset(ne, 0, sizeof(ne));
	memset(to, 0, sizeof(to));
	memset(match, 0, sizeof(match));
	tot = 0;
}

int main() {
	T = read();
	while (T--) {
		pre();
		n = read();
		for (int i = 1;i <= n; i++) 
		for (int j = 1;j <= n; j++) {
			int x = read();
			if (x) {
				add(i, j + n); add(j + n, i);
			}
		}
		int ans = 0;
		for (int i = 1;i <= n; i++) 
		tim++, ans += dfs(i);
		if (ans == n) printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}
posted @ 2019-10-05 23:15  Hs-black  阅读(121)  评论(0编辑  收藏  举报