最大匹配(简单版)

二分匹配——最大匹配

#include <cstdlib>
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;
const int maxn = 300;
vector<int>E[maxn];
int used[maxn];
int match[maxn];
int n,m;
void add_edge(int u,int v)
{
    E[u].push_back(v);
    E[v].push_back(u);
}
bool dfs(int x)
{
    used[x] = 1;
    for(int i = 0; i < E[x].size(); i ++)
    {
        int u = E[x][i];
        int v = match[u];
        if(v == -1 || used[v] == -1 && dfs(v))
        {
            match[u] = x;
            match[x] = u;
            return true;
        }
    }
    return false;
}
int max_match()
{
    int res = 0;
    memset(match,-1,sizeof(match));
    for(int i = 1; i <= m; i ++)
    {
        if(match[i] == -1)
        {
            memset(used,-1,sizeof(used));
            if(dfs(i))
                res ++;
        }
    }
    return res;
}
int main()
{
    scanf("%d %d",&n, &m);
    int u,v;
    while(scanf("%d %d",&u,&v)!=EOF)
    {
        add_edge(u,v);
    }
    int ans = max_match();
    printf("%d
",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/lcchy/p/10139463.html