矩阵游戏--二分图的匈牙利算法

发布于:2025-04-17 ⋅ 阅读:(84) ⋅ 点赞:(0)

https://www.luogu.com.cn/problem/P1129

学习路线---https://blog.csdn.net/qq_39304630/article/details/108135381

1.二分图就是两个独立的两个集合,如这里是行和列

2.匈牙利匹配就是媒婆拉媒,没伴侣或者伴侣可以换就将当前的塞给她

3.最后true的个数就算最小点覆盖数或者最大匹配数

#include<bits/stdc++.h>
#include<string>
using namespace std;
#define N 100011
typedef long long ll;
typedef pair<int,int> pii;
int t,n; 
int mp[201][201];
int mate[201];
bool bo[201];
bool metch(int x)///二分图--匈牙利算法 
{
	for(int j=1;j<=n;j++)
	{
		if(!bo[j]&&mp[x][j])///黑且没标记 
		{
			bo[j]=true;
			if(mate[j]==0||metch(mate[j]))///没伴侣或者j的伴侣可以换另一个 
			{
				mate[j]=x;///那j的伴侣现在就是x了 
				return true;///匹配成功 
			}
		}
	}
	return false;///一圈下来没有,失败qwq 
}
int main()
{
cin>>t;
while(t--)
{
	cin>>n;
	int s=0;
	memset(mate,0,sizeof(mate));///一定要清0!!!! 
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			cin>>mp[i][j];
			if(mp[i][j]) s++;
		}
	}
	if(s<n) cout<<"No";
	else
	{
		s=0;
		for(int i=1;i<=n;i++)
		{
			memset(bo,false,sizeof(bo));
			if(metch(i)) 
			{
				s++;
			}
		}
		if(s==n) cout<<"Yes";///行列不重复的要够n个
		else cout<<"No"; ///不够就百搭 
	}
	cout<<endl;
}
return 0;
}