P3386 【模板】二分图最大匹配

链接

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

思路

模版代码,重点在二分图和匈牙利算法这个知识点

代码

#include<bits/stdc++.h>
using namespace std;


#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define int long long

using namespace std;
const int N = 510;
int G[N][N], match[N], reserve_boy[N];
//匹配结果存在match中

int n, m;
bool dfs(int x)
{
	for (int i = 1; i <= m; i++)
	{
		if (!reserve_boy[i] && G[x][i])
		{
			reserve_boy[i] = 1;
			if (!match[i] || dfs(match[i]))
			{
				//两种情况:如果男孩i还没有配对,那么就分给女孩x
				//如果男孩i已经配对,尝试用dfs更换原配女孩,腾出位置给女孩x
				match[i] = x;
				return true;
			}
		}
	}
	//如果无法转移到新的上面,那就不同意
	return false;
}
signed main()
{
	IOS;
	int e; cin >> n >> m >> e;
	while (e--) { int a, b; cin >> a >> b; G[a][b] = 1; }
	int sum = 0;
	for (int i = 1; i <= n; i++)
	{
		memset(reserve_boy, 0, sizeof(reserve_boy));
		if (dfs(i))
			sum++;//为每个i女孩找配对
	}
	cout << sum;
	return 0;
}

posted @ 2025-02-20 16:52  WHUStar  阅读(1)  评论(0编辑  收藏  举报