L2-023 图着色问题 (25 分)

本文介绍了一种使用BFS算法解决彩色矩阵中颜色数等于k的同色连通问题的C++实现。博客核心在于理解如何通过广度优先搜索遍历矩阵并确保颜色分布符合要求。

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

https://pintia.cn/problem-sets/994805046380707840/problems/994805057298481152

思路:简单bfs,但是要注意颜色数一定要等于k。

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

const int maxn = 555;

int n, m, k, q;
int a[maxn][maxn], col[maxn], cnt[maxn], d[maxn];
bool st[maxn];

bool bfs()
{
    memset(st, 0, sizeof(st));
    queue<int>q;
    for(int i = 1;i <= n; i++)
    {
        if(!d[i]) st[i] = true;
    }
    int idx = 1;
    while(idx <= n)
    {
        while(st[idx]) idx++;
        q.push(idx);
        st[idx] = true;

        while(q.size())
        {
            int t = q.front();
            q.pop();

            for(int i = 1;i <= n; i++)
            {
                if(!a[t][i]) continue;
                if(col[i] == col[t]) return false;
                if(!st[i])
                {
                    st[i] = true;
                    q.push(i);
                }
            }
        }
    }
    return true;
}

int main()
{
    cin >> n >> m >> k;
    for(int i = 1;i <= m; i++)
    {
        int x, y;
        cin >> x >> y;
        a[x][y] = 1;
        a[y][x] = 1;
        d[x]++;
        d[y]++;
    }
    cin >> q;
    while(q--)
    {
        memset(cnt, 0, sizeof(cnt));
        for(int i = 1;i <= n; i++)
        {
            cin >> col[i];
            cnt[col[i]]++;
        }
        int flag = 0;
        for(int i = 1;i <= maxn; i++)
        {
            if(cnt[i] != 0) flag++;
        }
        if(flag != k)
        {
            puts("No");
            continue;
        }
        if(bfs()) puts("Yes");
        else puts("No");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值