PAT甲级 A1154 Vertex Coloring
问题描述
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
说人话
给出一个图的顶点数n和边数m,接着给出m条边,每条边用两个点表示(0~n-1)。然后给出k个查询数组,每个数组有n个值。每个值对应那个点的颜色,求在该图中每一条边两顶点颜色不相同的情况下。共用了多少种颜色
AC代码如下:
#include<cstdio>
#include<vector>
#include<unordered_set>
using namespace std;
int main(){
int n,m;
scanf("%d %d",&n,&m);
vector<int>v[n];//每个数组中存放着与该点共用一条边的另外一点
int a,b;
for(int i=0;i<m;i++){
scanf("%d %d",&a,&b);
v[a].push_back(b);
v[b].push_back(a);
}
int k;
scanf("%d",&k);
for(int i=0;i<k;i++){
vector<int>color(n);
int flag=1;
unordered_set<int>set;
for(int j=0;j<n;j++){
scanf("%d",&color[j]);
set.insert(color[j]);//利用set内元素不相同的性质求出颜色种类
}
for(int j=0;j<n-1;j++){
for(int k=0;k<v[j].size();k++){
if(color[j]==color[v[j][k]]){//若颜色相同,则不符合题意,跳出循环
flag=0;
break;
}
}
if(!flag)break;
}
if(flag){
printf("%d-coloring\n",(int)set.size());
}
else printf("No\n");
}
return 0;
}