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.
Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers N and M (both no more than 10
4
), being the total numbers of vertices and edges, respectively. Then M lines follow, each describes an edge by giving the indices (from 0 to N−1) of the two ends of the edge.
After the graph, a positive integer K (≤ 100) is given, which is the number of colorings you are supposed to check. Then K lines follow, each contains N colors which are represented by non-negative integers in the range of int. The i-th color is the color of the i-th vertex.
Output Specification:
For each coloring, print in a line k-coloring if it is a proper k-coloring for some positive k, or No if not.
Sample Input:
10 11
8 7
6 8
4 5
8 4
8 1
1 2
1 4
9 8
9 1
1 0
2 4
4
0 1 0 1 4 1 0 1 3 0
0 1 0 1 4 1 0 1 0 0
8 1 0 1 4 1 0 5 3 0
1 2 3 4 5 6 7 8 8 9
Sample Output:
4-coloring
No
6-coloring
No
题目大意:
给出一个图(先给出所有边,后给出每个点的颜色),问是否满足:所有的边的两个点的颜色不相同,若相同,则返回No,若不同,则输出颜色种数+"-coloring";
解题思路
①初始化一个图
②读取每个颜色序列
③运用BFS,依次判别两个节点颜色是否相同,若相同,返回fasle,否则输出颜色种数,统计颜色种数的时,用set来统计,set的去重性。
④check()函数用来检查非连通图
Code:
#include<iostream>
#include<vector>
#include<queue>
#include<set>
#include<algorithm>
#include<numeric>
using namespace std;
int N,M;
vector<vector<int>>Edge;
vector<int>visit;
vector<int>color;
bool BFS(int x){//BFS 架构
visit[x]=true;
queue<int>Q;//构造队列
Q.push(x);
while(!Q.empty()){
int T=Q.front();
Q.pop();
for(int i=0;i<Edge[T].size();i++){
if(color[T]==color[Edge[T][i]])
return false;//颜色相同 返回false 不再往下执行
if(!visit[Edge[T][i]]){
Q.push(Edge[T][i]);
visit[Edge[T][i]]=true;
}
}
}
return true;
}
bool check(){//若存在非连通图 也要对其进行BFS
fill(visit.begin(),visit.end(),0);
for(int i=0;i<N;i++){
if(!visit[i]&&!BFS(i))//若未被访问 则进行BFS 若返回false 说明存在颜色相同的两个节点 !BFS(i)=>true 直接跳False 下面节点不用遍历,输出No即可
return false;
}
return true;
}
int main(){
cin>>N>>M;
Edge.resize(N);
visit.resize(N);
for(int i=1;i<=M;i++){
int a,b;
cin>>a>>b;
Edge[a].push_back(b);//构造无向图
Edge[b].push_back(a);
}
int K;
cin>>K;
for(int i=1;i<=K;i++){
set<int>sum;
for(int j=1;j<=N;j++){
int col;
cin>>col;
color.push_back(col);
sum.insert(col);//统计颜色种数
}
if(!check())
cout<<"No";
else
cout<<sum.size()<<"-coloring";
if(i!=K)
cout<<endl;
fill(visit.begin(),visit.end(),0);//将visit数组重置为0 未被访问
color.clear();//把上次染色结果清空 方便下次染色
}
return 0;
}