HDU-2063 过山车(二分图最大匹配)

题意

给定 K 个可能组合, M 个女生, N 个男生,求最多产生多少队组合。
1 N , M 500
1 K 1000

思路

最大匹配入门题,重点介绍匈牙利算法。
该算法比较简单,可以近似的理解成一个抢老婆的过程。一开始集合 U 和集合 V 都没有被匹配,现在枚举集合 U 中的点,为集合 V 中的点选取最大匹配。当枚举到一个 u U 时,再枚举 e E u e = ( u , v ) 。当 v 未被匹配时,匹配 v 点,否则,尝试将 v 原先的匹配对象 m c v 重新匹配,( v 已被标记,无法被 m c v 再次匹配),比较好看出这是一个递归的过程,直到其中有个点能被重新匹配,或都不能重新匹配。

代码

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define FOR(i,x,y) for(int i=(x);i<=(y);i++)
#define DOR(i,x,y) for(int i=(x);i>=(y);i--)
#define N 503
typedef long long LL;
using namespace std;
template<const int maxn,const int maxm>struct Linked_list
{
    int head[maxn],to[maxm],nxt[maxm],tot;
    void clear(){memset(head,-1,sizeof(head));tot=0;}
    void add(int u,int v){to[++tot]=v,nxt[tot]=head[u],head[u]=tot;}
    #define EOR(i,G,u) for(int i=G.head[u];~i;i=G.nxt[i])
};
Linked_list<N,N<<1>G;
int mc[N],mark[N],n1,n2,m;

bool match(int u,int stmp)
{
    EOR(i,G,u)
    {
        int v=G.to[i];
        if(mark[v]==stmp)continue;
        mark[v]=stmp;
        if(!mc[v]||match(mc[v],stmp))
        {
            mc[v]=u;
            return true;
        }
    }
    return false;
}
int solve()
{
    int ans=0;
    memset(mc,0,sizeof(mc));
    memset(mark,0,sizeof(mark));
    FOR(i,1,n1)if(match(i,i))ans++;
    return ans;
}

int main()
{
    while(scanf("%d",&m),m)
    {
        scanf("%d%d",&n1,&n2);
        G.clear();
        FOR(i,1,m)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            G.add(u,v);
        }
        printf("%d\n",solve());
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Paulliant/article/details/81564416