zoukankan      html  css  js  c++  java
  • 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
    ");
    		else printf("No
    ");
    	}
    	return 0;
    }
    
  • 相关阅读:
    【BZOJ1046】[HAOI2007]上升序列
    【BZOJ1045】[HAOI2008]糖果传递
    【BZOJ1044】[HAOI2008]木棍分割
    【BZOJ1041】[HAOI2008]圆上的整点
    【LG2257】YY的GCD
    【BZOJ1018】[SHOI2008]堵塞的交通
    【LG4735】最大异或和
    【POJ2182】Lost Cows
    【POJ2482】Stars in Your Window
    【POJ1733】Parity game
  • 原文地址:https://www.cnblogs.com/Hs-black/p/11626125.html
Copyright © 2011-2022 走看看