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

思路:

用单链表存图,每次涂色每个颜色放set中,set的size就是用的颜色的种类。然后对于每次涂色,枚举每一个点,遍历这个点开头的链表,和这个点相邻的点有一个重色就是false,每一个点都是true结果才为yes。

坑点(测试点2):

一般我们的思维都会认为使用的颜色数小于等于k就合法,但题目的意思是使用的颜色书必须要等于k,所以把判断改成颜色数==k就可以了。

代码:

#include<iostream>
#include<cstdio>
#include<string.h>
#include<set>
using namespace std;
int v,m,k,n;
int h[510],color[510],e[250010],ne[250010],idx;
set<int> book;

void add(int a,int b){
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}

bool judge(int root){
    bool st=true;
    for(int i=h[root];i!=-1;i=ne[i]){
        if(color[root]==color[e[i]]){
            st=false;
            break;
        }
    }
    return st;
}

int main(){
    memset(h,-1,sizeof h);
    cin>>v>>m>>k;
    for(int i=0;i<m;i++){
        int a,b;
        cin>>a>>b;
        add(a,b),add(b,a);
    }
    cin>>n;
    for(int i=0;i<n;i++){
        book.clear();
        for(int j=1;j<=v;j++){
            cin>>color[j];
            book.insert(color[j]);
        }
        if(book.size()!=k){
            cout<<"No"<<endl;
            continue;
        }
        bool st=true;
        for(int j=1;j<=v;j++){
            if(!judge(j)) st=false;
        }
        if(st) cout<<"Yes"<<endl;
        else cout<<"No"<<endl;
    }
    system("pause");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值