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;
}