Fork me on GitHub

二分图最大匹配

#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
int n,m;
int num[20009],nxt[20009],head[10009],cnt=0,sum=0;
int book[10009],match[10009];
int dfs(int x)
{
    for(int i=head[x];i;i=nxt[i])
    {
        int k=num[i];
        if(book[k]==0)
        {
            book[k]=1;// 标记 k 
            if(match[k]==0||dfs(match[k]))//如果 k 还没有配对或者 k 的配对找到了其他的配对 
            {
                match[k]=x;
                match[x]=k;
                return 1;
            }
        }
    }
    return 0;
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        cnt++;
        num[cnt]=y;
        nxt[cnt]=head[x];
        head[x]=cnt;

        cnt++;
        num[cnt]=x;
        nxt[cnt]=head[y];
        head[y]=cnt;
    }

    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++) book[j]=0;
        if(dfs(i)) sum++;
    }

    printf("%d",sum);
    return 0;
} 

感谢《啊哈》

posted @ 2017-04-16 08:20  primes  阅读(80)  评论(0编辑  收藏  举报