NYOJ2444The Accomodation of Students

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2444


就是一个匈牙利算法模板题。


代码:

#include <cstdio>
#include <queue>
#include <cstring>

using namespace std;

int n,m;
int e[205][205];
int col[205];
int match[205];
int v[205];

void init()

{
    memset(col,-1,sizeof(col));
    memset(e,0,sizeof(e));
    memset(match,0,sizeof(match));
}
void input()

{
    for(int i = 0;i < m;++i)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        e[a][b] = e[b][a] = 1;
    }
}
bool bfs(int s)

{
    queue<int> q;
    q.push(s);
    col[s] = 1;
    while(!q.empty())
    {
        int head = q.front();
        q.pop();
        for(int i = 1;i <= n;++i)
        {
            if(e[head][i] && col[i] == -1)
            {
                col[i] = !col[head];
                q.push(i);
            }
            if(e[head][i] && col[i] == col[head])
                return false;
        }
    }
    return true;
}
bool isBiGraph()

{
    bool flag = true;
    for(int i = 1;i <= n;++i)
    {
        if(col[i] == -1 && !bfs(i))
        {
            flag = false;
            break;
        }
    }
    return flag;
}
bool dfs(int u)

{
    for(int i = 1;i <= n;++i)
    {
        if(!v[i] && e[u][i] == 1)
        {
            v[i] = 1;
            if(match[i] == 0 || dfs(match[i]))
            {
                match[i] = u;
                //match[u] = i;
                return true;
            }
        }
    }
    return false;
}
int MaxMatch()

{
    int ans = 0;
    for(int i = 1;i <= n;++i)
    {
        memset(v,0,sizeof(v));
        if(dfs(i))
            ans++;
    }
    return ans;
}
int main()

{
     while(~scanf("%d%d",&n,&m))
     {
         init();
         input();
         if(!isBiGraph())
               printf("No\n");
         else
            {
                printf("%d\n",MaxMatch() / 2);
            }
     }
     return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值