HDU2444_The Accomodation of Students _染色法判二分图&邻接矩阵二分图匹配模板

博客介绍了如何利用染色法判断一个图是否为二分图,并在确认为二分图后,通过邻接矩阵模板解决二分图的最大匹配问题。具体包括题意解析、思路分享以及AC代码展示,涉及HDU2444题目。
摘要由CSDN通过智能技术生成

题意

给 N 个点和若干条边。
第一问:判断是不是二分图
第二问:如果是二分图,求最大匹配

思路

第一问用染色法判二分图,第二问套模板

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=2444

AC代码

#include<cstdio>
#include<iostream>
#include<cstring>

using namespace std;

const int maxv = 200 + 10;

int N, M;

int Color[maxv];
bool Bg;

/***************************邻接矩阵二分图匹配模板***************************/
int V;
bool G[maxv][maxv];
int Match[maxv];
bool Vis[maxv];

bool dfs(int u)
{
    Vis[u] = true;

    for(int i= 1; i<= V; i++)
        if(G[u][i])
        {
            int w = Match[i];
            if(w < 0 || !Vis[w] && dfs(w))
            {
                Match[u] = i;
                Match[i] = u;
                return true;
            }
        }

    return false;
}

int max_match()
{
    int res = 0;
    memset(Match, -1, sizeof Match);

    for(int i= 1; i<= V; i++)
        if(Match[i] < 0)
        {
            memset(Vis, false, sizeof Vis);
            if(dfs(i)) res ++;
        }

    return res;
}
/***************************邻接矩阵二分图匹配模板***************************/

bool C(int u, int pre)
{
    if(Color[u] == 0)
    {
        Color[u] = pre * -1;
        for(int i= 1; i<= N; i++)
            if(G[u][i])
                if(!C(i, Color[u])) return false;
    }

    else if(Color[u] != pre * -1) return false;

    return true;
}

int main()
{
    while(scanf("%d %d", &N, &M) != EOF)
    {
        V = N;
        memset(G, false, sizeof G);
        for(int i= 1; i<= M; i++)
        {
            int x, y;
            scanf("%d %d", &x, &y);
            G[x][y] = G[y][x] = true;
        }

        Bg = true;
        memset(Color, 0, sizeof Color);
        for(int i= 1; i<= N; i++)
        {
            if(Color[i] == 0) Bg &= C(i, -1);
            if(!Bg) break;
        }

        if(!Bg)
        {
            printf("No\n");
            continue;
        }

        printf("%d\n", max_match());
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值