hihocoder 1122最大二分匹配匈牙利算法

本文介绍了一种基于图的匹配算法实现,通过构建图结构并利用路径搜索的方式寻找最大匹配。文章详细展示了算法的具体实现过程,包括节点定义、图的构建方式、最大匹配路径的查找等关键步骤,并提供了一个完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cstring>
#include <stack>
#include <set>
#include <map>
#include <vector>

using namespace std;
#define INF 0x2fffffff
#define LL long long
#define MAX(a,b) ((a)>(b))?(a):(b)
#define MIN(a,b) ((a)<(b))?(a):(b)
struct node{
    int from,to,next;
};
node es[10005];
int head[1005];
int cnt;
int vis[1005];
int c[1005];
int n,m;
int add(int from,int to){
    es[cnt].from = from ;
    es[cnt].to = to;
    es[cnt].next = head[from];
    head[from] = cnt++;
}
int path(int x){
    for(int t = head[x];t != 0;t = es[t].next){
        if(!vis[es[t].to]){
            vis[es[t].to] = 1;
            if(!c[es[t].to] || path(c[es[t].to])){
                c[es[t].to] = x;
                c[x] = es[t].to;
                return 1;
            }
        }
    }
    return 0;
}
int max_flow(){
    memset(c,0,sizeof(c));
    int ans = 0;
    for(int i = 1;i <= n;i++){
        if(!c[i]){
            memset(vis,0,sizeof(vis));
            ans += path(i);
        }
    }
    return ans;
}
int main(){
    while(cin >> n >> m){
        memset(head,0,sizeof(head));
        cnt = 1;
        for(int i = 0;i < m;i++){
            int x,y;
            scanf("%d%d",&x,&y);
            add(x,y);
            add(y,x);
        }
        cout << max_flow() << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值