acwing算法基础之搜索与图论--匈牙利算法求二分图的最大匹配数

目录

  • [1 基础知识](#1 基础知识)
  • [2 模板](#2 模板)
  • [3 工程化](#3 工程化)

1 基础知识

二分图中的最大匹配数:从二分图中选择一些边(这些边连接集合A和集合B,集合A中结点数目为n1,集合B中结点数目为n2),设为集合S,其中任意两条边不共用一个结点。求集合S的最大元素数目,即二分图中的最大匹配数。

匈牙利算法的关键步骤:

  1. 初始化匹配数组match1\~n2 = 0。其中matchb = a,表示集合B中的结点b匹配了集合A中的结点a。
  2. 遍历集合A中的每一个结点a:初始化状态数组st1\~n2 = false,其中stb = false表示集合B中的结点b没有被访问。然后,find(x),如果它返回true,那么答案加1。
cpp 复制代码
bool find(int a) {//a为集合A中的结点
	for (auto b : g[x]) {
		if (!st[b]) {//如果结点b没有被访问
			st[b] = true;
			if (match[b] == 0 || find(match[b])) { //如果结点b没有被匹配,或者结点b匹配了的结点可以找到新的
				match[b] = a;
				return true;
			}
		}
	}
	return false;
}
  1. 最终返回答案,即为该二分图的最大匹配数。

2 模板

cpp 复制代码
int n1, n2;     // n1表示第一个集合中的点数,n2表示第二个集合中的点数
int h[N], e[M], ne[M], idx;     // 邻接表存储所有边,匈牙利算法中只会用到从第一个集合指向第二个集合的边,所以这里只用存一个方向的边
int match[N];       // 存储第二个集合中的每个点当前匹配的第一个集合中的点是哪个
bool st[N];     // 表示第二个集合中的每个点是否已经被遍历过

bool find(int x)
{
    for (int i = h[x]; i != -1; i = ne[i])
    {
        int j = e[i];
        if (!st[j])
        {
            st[j] = true;
            if (match[j] == 0 || find(match[j]))
            {
                match[j] = x;
                return true;
            }
        }
    }

    return false;
}

// 求最大匹配数,依次枚举第一个集合中的每个点能否匹配第二个集合中的点
int res = 0;
for (int i = 1; i <= n1; i ++ )
{
    memset(st, false, sizeof st);
    if (find(i)) res ++ ;
}

3 工程化

题目1:求二分图的最大匹配。

cpp 复制代码
#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

const int N = 510;
int n1, n2, m;
vector<vector<int>> g(N);
int match[N];
bool st[N];

bool find(int a) {
    for (auto b : g[a]) {
        if (!st[b]) {
            st[b] = true;
            if (match[b] == 0 || find(match[b])) {
                match[b] = a;
                return true;
            }
        }
    }
    return false;
}

int main() {
    cin >> n1 >> n2 >> m;
    int a, b;
    while (m--) {
        cin >> a >> b;
        g[a].emplace_back(b);
    }
    
    int res = 0;
    for (int i = 1; i <= n1; ++i) {
        memset(st, 0, sizeof st);
        if (find(i)) res++;
    }
    
    cout << res << endl;
    
    return 0;
}
相关推荐
小L~~~9 小时前
基于贪心策略的混合遗传算法求解01背包问题
python·算法
洛水水9 小时前
【力扣100题】53.最长回文子串
算法·leetcode·职场和发展
jieyucx9 小时前
Go 语言 sort 包详解:从基础排序到自定义排序(含底层原理+零基础看懂)
算法·golang·排序算法·sort
叁散10 小时前
ESP32 LCD1602显示实验报告
算法
过期动态10 小时前
【LeetCode 热题 100】盛最多水的容器
java·数据结构·spring boot·算法·leetcode·spring cloud·职场和发展
凌波粒10 小时前
LeetCode--700.二叉搜索树中的搜索(二叉树)
算法·leetcode·职场和发展
君为先-bey10 小时前
LeMiCa——基于扩散模型的高效视频生成的词典序最小化路径缓存
python·算法·机器学习·扩散模型
洛水水11 小时前
【力扣100题】58.轮转数组
算法·leetcode
资深流水灯工程师11 小时前
LMS 最小均方算法在 DSP 上的 C 语言实现
算法
风筝在晴天搁浅11 小时前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表