P3386 【模板】二分图匹配

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37275680/article/details/82020353

传送门:P3386 【模板】二分图匹配

二分图的最大匹配最常用的算法是匈牙利算法,即由增广路求最大匹配。

详解请点击右侧链接:趣写算法系列之--匈牙利算法

//二分图的最大匹配——匈牙利算法,即由增广路求最大匹配
//#define LOCAL
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1010;
int n,m,e,vis[maxn],link[maxn],mp[maxn][maxn];

bool match(int x){
    for(int i=1;i<=m;i++){
        if(mp[x][i]&&!vis[i]){
            vis[i]=1;
            if(link[i]==-1||match(link[i])){
                link[i]=x;
                return true;
            }
        }
    }
    return false;
}

int hungry(){
    int tot=0;
    memset(link,-1,sizeof(link));
    for(int i=1;i<=n;i++){
        memset(vis,0,sizeof(vis));
        if(match(i)) tot++;
    }
    return tot;
}

int main(){
#ifdef  LOCAL
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
#endif
    scanf("%d%d%d",&n,&m,&e);
    int u,v;
    memset(mp,0,sizeof(mp));
    for(int i=0;i<e;i++){
        scanf("%d%d",&u,&v);
        if(u<=n&&v<=m)
            mp[u][v]=1;
    }

    int cnt=hungry();
    printf("%d\n",cnt);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37275680/article/details/82020353