acwing 861 二分图的最大匹配 (匈牙利算法)

题面

在这里插入图片描述

题解

  1. 匈牙利算法:求一个二分图的最大匹配数,O(nm),实际远小于这个时间复杂度,,遵循“先到先得,能让则让”的原则

在这里插入图片描述
2. 模拟过程:1匹配最先的6,2匹配最先的7,3只有一个能匹配的6,但是6已经让1匹配,我们就需要看6所匹配的点1能否去匹配别的点,发现1除了能匹配6,还可以匹配8,所以就让1匹配8,3匹配6,4匹配7

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 1e5 + 10;


int n1, n2, m;
int h[N], e[N], ne[N], idx;
int match[N];  //存储每个点当前匹配的点
bool st[N];    //表示每个点是否已经被遍历过

void add(int a, int b) {
    
    
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx++;
}

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 main() {
    
    

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    memset(h, -1, sizeof h);

    cin >> n1 >> n2 >> m;

    for (int i = 1; i <= m; i++) {
    
    
        int a, b;
        cin >> a >> b;
        add(a, b);
    }

    int res = 0;
    for (int i = 1; i <= n1; i++) {
    
    
        memset(st, false, sizeof st);
        if (find(i)) res++;
    }

    cout<<res<<endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/114578300