C - Bicoloring

本文深入探讨了二分图匹配算法的实现细节,通过一个具体的C++代码示例,展示了如何使用广度优先搜索(BFS)来解决二分图的可二色性问题。代码中定义了一个二维数组p用于存储图的邻接矩阵,一维数组v和c分别用于记录顶点的状态和颜色。通过bfs函数检查图是否可以被正确地二色划分,并返回相应的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://vjudge.net/contest/278989#problem/C


#include <cstdio>
#include <string.h>
#include <queue>
using namespace std;

int p[205][205];
int v[205], m, n;
bool c[205];

bool bfs()
{
    queue <int> q;
    q.push(0);
    v[0] = 1;
    c[0] = true;
    while (!q.empty())
    {
        int t = q.front();
        q.pop();
        for (int i = 0; i < n; i++)
        {
            if (p[t][i])
            {
                if (!v[i])
                {
                    q.push(i);
                    v[i] = 1;
                    c[i] = !c[t];
                }
                else
                {
                    if (c[i] == c[t])
                        return  false;
                }
                p[t][i] = 0;
            }
        }
    }
    return true;
}

int main()
{
    while (scanf("%d", &n) && n != 0)
    {
        memset(p, 0, sizeof(p));
        memset(v, 0, sizeof(v));
        memset(c, 0, sizeof(c));
        int t1, t2;
        scanf("%d", &m);
        for (int i = 0; i < m; i++)
        {
            scanf("%d%d", &t1, &t2);
            p[t1][t2] =1;
        }
        if (bfs())
            printf("BICOLORABLE.\n");
        else
            printf("NOT BICOLORABLE.\n");
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值