HDU 2444 The Accomodation of Students(最大二分匹配(匈牙利算法)+二分图判断->模板题目)

这道题首先判断一下图是不是二部图,如果是的话,就进行二分匹配

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 300;
int n, m;
int color[N];
int g[N][N], linker[N];
bool used[N];

bool dfs( int u ) 
{
    int i;
    for ( i = 1; i <= n; ++i ) if ( g[u][i] ) {
        if ( !used[i] ) {
            used[i] = true;
            if ( linker[i] == -1 || dfs(linker[i]) ) {
               linker[i] = u;
               return true;
            }
        }
    }
    return false;
}
int match()
{
    int res = 0;
    memset( linker, -1, sizeof(linker));
    for ( int u = 1; u <= n; ++u ) {
        memset( used, 0, sizeof(used) );
        if ( dfs( u ) ) res++;
    }
    return res;
}
bool bipartite( int x )
{
    for ( int i = 1; i <= n; ++i ) {
        if ( g[x][i] && color[i] == color[x] ) return false;
        if ( g[x][i] && !color[i] ) {
            color[i] = 3-color[x];
            if ( !bipartite(i) ) return false;
        }
    }
    return true;
}
int main()
{
    while ( scanf("%d%d", &n, &m) == 2 ) {
        memset( g, 0, sizeof(g));
        memset( color, 0, sizeof(color));
        for ( int i = 1; i <= m; ++i ) {
            int u, v;
            scanf("%d%d", &u, &v);
            g[u][v] = g[v][u] = 1;
        }
        color[1] = 1;
        if ( !bipartite(1) ) {
            printf("No\n");
            continue;
        }
        printf("%d\n", match()/2);
    }
}
        


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值