zoukankan      html  css  js  c++  java
  • 洛谷P1129 [ZJOI2007] 矩阵游戏(二分图最大匹配)

    最终(mtx[i][i])为黑色的,实际上相当于每行和每列进行了匹配。如果只看对角线其他地方全看作白色的话,交换行列后每行和每列还是匹配的,只不过匹配的对象变了。因此交换行列并不改变最终匹配的状态(可以联想线性代数里的行变换等等)。因此把行看作左部点,列看作右部点,每个黑点看作连接行列的边,跑匈牙利求最大匹配,如果最大匹配是完美匹配的话说明有解。

    注意数组都要开的大一点,因为蓝书匈牙利板子用的是邻接表,而此题算是稠密图,2e2平方后就是4e4了...在这wa了一发QAQ

    #include <iostream>
    #include <cstring>
    using namespace std;
    int n, match[40005];
    bool mtx[205][205], vis[40005];
    int head[40005], ver[80005], Next[80005], tot = 0;
    void add(int x, int y)
    {
    	ver[++tot] = y, Next[tot] = head[x], head[x] = tot;
    }
    bool dfs(int x)
    {
    	for(int i = head[x], y; i; i = Next[i])
    	{
    		if(!vis[y = ver[i]])
    		{
    			vis[y] = 1;
    			if(!match[y] || dfs(match[y])){
    				match[y] = x;
    				return 1;
    			}
    		}
    	}
    	return 0;
    }
    int main()
    {
    	freopen("data.txt", "r", stdin);
    	ios::sync_with_stdio(false); 
    	int t;
    	cin >> t;
    	while(t--)
    	{
    		cin >> n;
    		tot = 0;
    		memset(match, 0, sizeof(match));
    		memset(head, 0, sizeof(head));
    		for(int i = 1; i <= n; i++)
    		{
    			for(int j = 1; j <= n; j++)
    			{
    				cin >> mtx[i][j];
    			}
    		}
    		for(int i = 1; i <= n; i++)
    		{
    			for(int j = 1; j <= n; j++)
    			{
    				if(mtx[i][j] == 1)
    				{
    					add(i, j + n);
    					add(j + n, i);
    				}
    			}
    		}
    		int ans = 0;
    		for(int i = 1; i <= n; i++)
    		{
    			memset(vis, 0, sizeof(vis));
    			if(dfs(i))
    			{
    				ans++;
    			}
    		}
    		if(ans == n) cout << "Yes" << endl;
    		else cout << "No" << endl;
    	}
    	
    	return 0;
    }
    
  • 相关阅读:
    linux笔记2.20
    新安装ubuntu后几项配置
    linux网络配置
    linux笔记2.19
    jquery在不同浏览器获取文件路径出现问题!
    软件工程师如何定义自己的职业路线
    标识符
    结对项目-四则运算 “软件”之升级版
    小学四则运算 “软件”之初版
    分布式版本控制系统Git的安装与使用
  • 原文地址:https://www.cnblogs.com/lipoicyclic/p/14412061.html
Copyright © 2011-2022 走看看