题目
坑
颜色个数必须是k个,多了少了都不行。图不一定联通。
代码
拿这个题练了一下链式向前星。
#include <cstdio>
#include <cstring>
#include <set>
using namespace std;
const int maxn = 505;
struct Edge{
int to, next;
Edge() {
to = next = -1;
}
}edge[maxn*maxn];
int head[maxn];
int tot = -1;
void add(int u, int v) {
++tot;
edge[tot].to = v;
edge[tot].next = head[u];
head[u] = tot;
}
bool vis[maxn];
int color[maxn];
set<int> col;
bool dfs(int u) {
if(vis[u]) return true;
vis[u] = true;
int i = head[u];
while(i != -1) {
if(color[u] == color[edge[i].to])
return false;
i = edge[i].next;
}
for(int i = head[u]; i != -1; i = edge[i].next) {
if(!dfs(edge[i].to))
return false;
}
return true;
}
int main(void)
{
freopen("in.txt", "r", stdin);
int v, e, k;
scanf("%d%d%d", &v, &e, &k);
int a, b;
for(int i = 0; i < maxn; ++i) {
head[i] = -1;
}
while(e--) {
scanf("%d%d", &a, &b);
add(a, b);
add(b, a);
}
int n;
scanf("%d", &n);
while(n--) {
memset(vis, 0, sizeof(vis));
col.clear();
for(int i = 1; i <= v; ++i) {
scanf("%d", &color[i]);
col.insert(color[i]);
}
if(col.size() != k) {
puts("No");
continue;
}
bool flag = true;
for(int i = 1; i <= v; ++i) {
if(!dfs(i)) {
flag = false;
break;
}
}
if(flag)
puts("Yes");
else puts("No");
}
return 0;
}