思路:
用单链表存图,每次涂色每个颜色放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");
}