目录

​1,题目描述​

​题目大意​

​2,思路​

​3,AC代码​

​4,解题过程​


1,题目描述

PAT_甲级_1154 Vertex Coloring (25point(s)) (C++)【图的遍历/】_1154

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

题目大意

(也是离散数学里的经典题目)

判断任意相邻两点颜色是否相同,若均不相同输出不同的颜色数目;

 

2,思路

邻接矩阵存放图;

遍历任意相邻两点,判断两点颜色是否相同,并用unordered_set<int> record记录颜色种类数目;

若任意相邻两点颜色均不相同,输出record.size()即颜色种类数;

 

3,AC代码

#include<bits/stdc++.h>
using namespace std;
int N, M, K;
vector<int> graph[10005];
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
scanf("%d%d", &N, &M);
int a, b;
while(M--){
scanf("%d%d", &a, &b);
graph[a].push_back(b);
graph[b].push_back(a);
}
scanf("%d", &K);
int color[10005];
while(K--){
unordered_set<int> record; //记录颜色种类数目
for(int i = 0; i < N; i++){
scanf("%d", &color[i]);
record.insert(color[i]);
}
bool flag = true;
for(int i = 0; i < N; i++){ //遍历任意两个相邻节点 判断颜色是否相同
for(auto j: graph[i])
if(color[i] == color[j]){
flag = false;
break;
}
if(flag == false) break;
}
if(flag) printf("%d-coloring\n", record.size());
else printf("No\n");
}
return 0;
}

 

4,解题过程

一发入魂o(* ̄▽ ̄*)ブ

PAT_甲级_1154 Vertex Coloring (25point(s)) (C++)【图的遍历/】_甲级_02