思路:
利用广度优先搜索 BFS,匹配节点与附近节点颜色是否不一样,同时需要考虑非连通图的情况,颜色的数量可以用 set 记录。
1154 Vertex Coloring (25 point(s))
A proper vertex coloring is a labeling of the graph's vertices with colors such that no two vertices sharing the same edge have the same color. A coloring using at most k colors is called a (proper) k-coloring.
Now you are supposed to tell if a given coloring is a proper k-coloring.
Example:
#include<iostream>
#include<vector>
#include<queue>
#include<set>
using namespace std;
struct Graph {
int Nv;
int Ne;
vector<set<int>> G;
};
int coloring(Graph &G, vector<int> &color)
{
set<int> mark;
queue<int> Q;
vector<bool> visited(G.Nv, false);
for(int i = 0; i < G.Nv; i++) {
if(!visited[i]) {
Q.push(i);
mark.insert(color[i]);
visited[i] = true;
while(!Q.empty()) {
int front = Q.front();
for(auto &x : G.G[front]) {
if(color[x] == color[front]) return 0;
if(!visited[x]) {
Q.push(x);
visited[x] = true;
mark.insert(color[x]);
}
}
Q.pop();
}
}
}
return mark.size();
}
int main()
{
int N, M, K;
cin >> N >> M;
Graph G;
G.Nv = N, G.Ne = M, G.G.resize(N);
for(int i = 0; i < M; i++) {
int v1, v2;
cin >> v1 >> v2;
G.G[v1].insert(v2);
G.G[v2].insert(v1);
}
cin >> K;
vector<int> color(N);
for(int i = 0; i < K; i++) {
for(int j = 0; j < N; j++) cin >> color[j];
int result = coloring(G, color);
if(result > 0) printf("%d-coloring\n", result);
else cout << "No\n";
}
}