【BZOJ1059】[ZJOI2007]矩阵游戏【二分图匹配】

题意:

给出一个01矩阵,可以交换任意行,交换任意列。问是否可以把这个矩阵的对角线都变为1。


http://www.cnblogs.com/jianglangcaijin/p/3799615.html说的挺详细的。


#include <cstdio>

using namespace std;

const int maxn = 405, maxm = 40005;

int n, head[maxn], cnt, from[maxn], vis[maxn], clo;

struct _edge {
	int v, next;
} g[maxm];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void add(int u, int v) {
	g[cnt] = (_edge) {v, head[u]};
	head[u] = cnt++;
}

bool hungary(int x) {
	for(int i = head[x]; ~i; i = g[i].next) if(vis[g[i].v] != clo) {
		vis[g[i].v] = clo;
		if(!from[g[i].v] || hungary(from[g[i].v])) {
			from[g[i].v] = x;
			return 1;
		}
	}
	return 0;
}			

int main() {
	int T = iread();
	while(T--) {
		n = iread();
		for(int i = n << 1; i >= 1; i--) from[i] = vis[i] = 0, head[i] = -1; cnt = 0;

		for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) if(iread()) add(i, j + n);

		int ans = 0; clo = 0;
		for(int i = 1; i <= n; i++) clo++, ans += hungary(i);

		printf(ans == n ? "Yes\n" : "No\n");
	}
	return 0;
}


你可能感兴趣的:(二分图匹配)