PAT_A1154#Vertex Coloring
Source:
Description:
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 1), 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 properk
-coloring for some positivek
, orNo
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
Keys:
- 图的存储和遍历
- set(C++ STL)
- 散列(Hash)
Attenrion:
- 矩阵存储图,规模小于10^3
- 对于多组测试用例的输入,要注意统计值和哈希函数的初始化(出题老师太坏了,测试用例即使不初始化也是对的-,-)
Code:
1 /* 2 Data: 2019-08-02 21:08:29 3 Problem: PAT_A1154#Vertex Coloring 4 AC: 17:39 5 6 题目大意: 7 判断图中相连的顶点是否共色 8 */ 9 #include<cstdio> 10 #include<set> 11 using namespace std; 12 const int M=1e4+10; 13 struct node 14 { 15 int u,v; 16 }grap[M]; 17 int color[M]; 18 19 int main() 20 { 21 #ifdef ONLINE_JUDGE 22 #else 23 freopen("Test.txt", "r", stdin); 24 #endif // ONLINE_JUDGE 25 26 int n,m,k; 27 scanf("%d%d", &m,&n); 28 for(int i=0; i<n; i++) 29 scanf("%d%d", &grap[i].u,&grap[i].v); 30 scanf("%d", &k); 31 while(k--) 32 { 33 set<int> mp; 34 for(int i=0; i<m; i++) 35 { 36 scanf("%d", &color[i]); 37 mp.insert(color[i]); 38 } 39 for(int i=0; i<n; i++) 40 { 41 if(color[grap[i].u] == color[grap[i].v]) 42 { 43 mp.clear(); 44 break; 45 } 46 } 47 if(mp.size()) 48 printf("%d-coloring\n", mp.size()); 49 else 50 printf("No\n"); 51 } 52 53 return 0; 54 }