首页 技术 正文
技术 2022年11月19日
0 收藏 829 点赞 4,905 浏览 1270 个字

题目链接:http://poj.org/problem?id=1274

题目意思:有 n 头牛,m个stall,每头牛有它钟爱的一些stall,也就是几头牛有可能会钟爱同一个stall,问牛与 stall 最大匹配数是多少。

二分图匹配,匈牙利算法入门题,留个纪念吧。

书上看到的一些比较有用的知识点:

增广:通俗地说,设当前二分图中,已有 x 个匹配边(也就是假设代码中match[i] 不为0的个数有x个),现在对 i 点(也就是代码中dfs中的参数 x) 指定一个匹配点 j, 由于 j 可能有匹配点设为 k(map[x][i]),必须要为k找到一个新匹配 (对应黑屏中的前两次增广,本来的match[2] 从 1 变为 2 了,因为要为牛2找stall ,遇到map[2][2]边的时候发现match[2] 有数,只能调用dfs(match[2]) 为 match[2]找另一个匹配,也就是map[1][5],发现能找到,于是match[5] = 1,match[2] 就顺利成章变为2了)。

poj  1274 The Perfect Stall  解题报告

若能够找到,则表示匹配成功了x + 1 条边;若不能找到,相当于还是只有 x 个匹配边,只不过换了一种匹配方案而已,若达不到增加一条边的目的则称为对 i 增广不成功。

 #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring> using namespace std;
const int maxn = + ; int map[maxn][maxn];
int match[maxn]; // match[m]存储了匹配的方案, match[i] = j :仓库i里是牛j
bool vis[maxn];
int n, m, cnt; int dfs(int x) // 深搜找增广路径
{
for (int i = ; i <= m; i++)
{
if (!vis[i] && map[x][i]) // 对x的每个邻接点
{
vis[i] = true;
if (match[i] == || dfs(match[i])) // 若 match[i] 点是一个初始值,表示i点原来没有匹配,则增广成功返回
{ // 或者 match[i]点能重新找到一个新的匹配点
match[i] = x; // 保证新的匹配方案
return ;
}
}
}
return ;
} void Hungary()
{
cnt = ;
for (int i = ; i <= n; i++) // 对 n 个点依次进行增广
{
memset(vis, , sizeof(vis));
cnt += dfs(i); // 增广成功,表示i点找到了一个匹配,多了一条匹配边
}
} int main()
{
int k, to; // k: stall_num, to:stall_id
while (scanf("%d%d", &n, &m) != EOF)
{
memset(map, , sizeof(map));
memset(match, , sizeof(match)); for (int i = ; i <= n; i++)
{
scanf("%d", &k);
for (int j = ; j <= k; j++)
{
scanf("%d", &to);
map[i][to] = ;
}
}
Hungary();
printf("%d\n", cnt);
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,557
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898