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;
    }
    
  • 相关阅读:
    12306抢票系统——ER图及数据表
    深度学习攻防对抗(JCAI-19 阿里巴巴人工智能对抗算法竞赛)
    用Tensorflow实现DCGAN
    机器学习实战:数据预处理之独热编码(One-Hot Encoding)
    K最近邻算法
    正则表达式模块re
    2013百度研发笔试
    python初准备:安装easy_install和pip
    网络设备作用和工作ISO层
    01背包初始化的理解
  • 原文地址:https://www.cnblogs.com/lipoicyclic/p/14412061.html
Copyright © 2011-2022 走看看