Graph Coloring

本文探讨了一个问题,即在给定一组相连点的初始状态均为白色的情况下,如何通过染色某些点(限制相邻点不能同时为黑色)来达到最大数量的黑点,并输出所有可能的染色方案。

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

题意:给出一些相连的点,初始均为白色。现在将其中的一些点染成黑色,但是相邻的两个点不能同时为黑色。问最多有多少个黑点,并且把这些点输出。

思路:dfs。

#include<iostream>
#include<string.h>
using namespace std;
int map[105][105];
int sumStep,tmp,step[105];
int color[105];
int n,m;
void dfs(int t)
{
    int flag;
    for(color[t]=0; color[t]<=1; color[t]++) //color[t]表示第t个点的颜色,0为白,1为黑
    {
        flag=0;
        if(color[t])
        {
            for(int i=1; i<t; i++)//判断t点以前的与其相连的点是否为黑
                if(color[i]&&map[i][t])
                {
                    flag=1;
                    break;
                }
        }
        if(flag)
            continue;
        tmp+=color[t];
        if(t<n)
            dfs(t+1);
        else
        {
            if(sumStep<tmp)
            {
                sumStep=tmp;
                for(int i=1; i<=n; i++)//每次都要更换数组step
                step[i]=color[i];
            }
        }
        tmp-=color[t];//回溯
    }
}
int main()
{
    int tt;
    int a,b;
    cin>>tt;
    while(tt--)
    {
        memset(map,0,sizeof(map));
        sumStep=0;
        tmp=0;
        cin>>n>>m;
        while(m--)
        {
            cin>>a>>b;
            map[a][b]=map[b][a]=1;
        }
        dfs(1);
        cout<<sumStep<<endl;
        for(int i=1; i<=n; i++)
            if(step[i])
            cout<<i<<" ";
        cout<<endl;
    }
    return 0;
}
/*
1
6 8
1 2
1 3
2 4
2 5
3 4
3 6
4 6
5 6
*/


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值