匈牙利算法【模板】


代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
using namespace std;
const int maxn=105;
int n,m;
int match[maxn];
int vis[maxn];
int e[maxn][maxn];
int dfs(int u){
    for(int i=1;i<=n;i++){
        if(!vis[i]&&e[u][i]==1){
            vis[i]=1;//标记顶点i已访问过
            if(!match[i]||dfs(match[i])){//如果点i未被配对或者找到了新的配对、
                match[i]=u;//更新配对关系
                match[u]=i;
                return 1;
            }
        }
    }
    return 0;
}
int main()
{
    int u,v;
    int sum=0;
    scanf("%d %d",&n,&m);
    for(int i=1;i<=m;i++){
        scanf("%d %d",&u,&v);
        e[u][v]=e[v][u]=1;
    }
    for(int i=1;i<=n;i++)
        match[i]=0;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++)
            vis[j]=0;//清空上次搜索时的标记
        if(dfs(i)) sum++;//寻找增广路,如果找到,配对数加1
    }
    printf("%d\n",sum);
    return 0;
}
/*
6 5
1 4
1 5
2 5
2 6
3 4
*/

猜你喜欢

转载自blog.csdn.net/qq_37867156/article/details/80784794