过山车 邻接表 匈牙利算法

本文介绍了一种求解二分图最大匹配问题的算法实现,通过使用邻接表或邻接矩阵存储图结构,并结合深度优先搜索进行匹配对的寻找,实现了高效的匹配算法。该算法适用于解决诸如男女配对等实际问题。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>   
using namespace std;
const int maxn=505;
int n,m,k;
vector<int>G[maxn];  二维数组存输入的数据不必每个点都遍历效率高
bool vis[maxn];
int match[maxn];
void add(int a,int b){
    G[a].push_back(b);
}
int find(int s){
    for(int i=0;i<G[s].size();i++){
        int e=G[s][i];   男生的匹配
        if(!vis[e]){
            vis[e]=1;
            while(!match[e]||find(match[e])){
                    match[e]=s;
                  return true;
            }
        }
    }
    return false;
}
int Match(){
    int sum=0;
    for(int i=1;i<=m;i++){
        memset(vis,0,sizeof(vis));
        if(find(i))sum++;
    }
    return sum;
}
int main(){
    while(cin>>k){
        if(!k)break;
        memset(match,0,sizeof(match));
        for(int i=0;i<maxn;i++)G[i].clear();
        cin>>m>>n;
        int a,b;
        for(int i=1;i<=k;i++){
            cin>>a>>b;
            add(a,b);
        }
        cout<<Match()<<endl;
    }
    return 0;
}


 

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 505;
int G[maxn][maxn];
int match[maxn];
bool vis[maxn];
int k,m,n;
bool find(int s){
    for(int j=1;j<=n;j++)if(G[s][j]){
        if(!vis[j]){
            vis[j]=true;
            while(!match[j]||find(match[j])){
                match[j]=s;
                return true;
            }
        }
    }
    return false;
}
int Match(){
    int sum=0;
    for(int i=1;i<=m;i++){
        memset(vis,0,sizeof(vis));
        if(find(i))sum++;
    }
    return sum;
}

int main(){
    while(cin>>k){
        if(!k)break;
        memset(match,0,sizeof(match));
        memset(G,0,sizeof(G));
        cin>>m>>n;
        int a,b;
        for(int i=1;i<=k;i++)
        {
            cin>>a>>b;
            G[a][b]=1;
        }
        cout<<Match()<<endl;
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值