PAT_A1154#Vertex Coloring
Source:
PAT A 1154 Vertex Coloring (25 分)
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-05-10 20:56:31 3 Problem: PAT_A1154#Vertex Coloring 4 AC: 17:39 5 */ 6 7 #include<cstdio> 8 #include<set> 9 using namespace std; 10 const int M=1e4+10; 11 struct node 12 { 13 int v1,v2; 14 }grap[M]; 15 int c[M],n,m,k; 16 set<int> color; 17 18 int IsColoring() 19 { 20 for(int i=0; i<m; i++) 21 if(c[grap[i].v1] == c[grap[i].v2]) 22 return 0; 23 return 1; 24 } 25 26 int main() 27 { 28 #ifdef ONLINE_JUDGE 29 #else 30 freopen("Test.txt", "r", stdin); 31 #endif 32 33 scanf("%d%d", &n,&m); 34 for(int i=0; i<m; i++) 35 scanf("%d%d", &grap[i].v1,&grap[i].v2); 36 scanf("%d", &k); 37 for(int i=0; i<k; i++) 38 { 39 color.clear(); 40 for(int j=0; j<n; j++) 41 { 42 scanf("%d", &c[j]); 43 color.insert(c[j]); 44 } 45 if(IsColoring()) 46 printf("%d-coloring\n", color.size()); 47 else 48 printf("No\n"); 49 } 50 51 return 0; 52 }
PAT_A1154#Vertex Coloring