PAT甲級1154 Vertex Coloring (25分)|C++實現
一、題目描述
原題連結
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:
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
二、解題思路
給定一個圖,對圖中的結點進行“塗色”,要求判斷一條邊的兩端的結點是否都是相同顏色,如果不是,將顏色種數輸出。不太難,用set存放出現過的顏色,用鄰接表儲存這個圖,遍歷所有結點,如果有某個結點與連線著的結點顏色相同,那麼就將flag設為false。程式碼比較易懂,可參考程式碼註釋。
三、AC程式碼
#include<iostream>
#include<cstdio>
#include<vector>
#include<set>
using namespace std;
int main()
{
int N, M, K, tmp1, tmp2;
scanf("%d%d", &N, &M);
vector<int> Adj[N]; //鄰接表
for(int i=0; i<M; i++)
{
scanf("%d%d", &tmp1, &tmp2);
Adj[tmp1].push_back(tmp2); //鄰接表
}
scanf("%d", &K);
for(int i=0; i<K; i++)
{
int color[N];
set<int> col; //用於存放出現了的顏色
bool flag = true;
for(int j=0; j<N; j++)
{
scanf("%d", &color[j]); //存放j結點對應的顏色
col.insert(color[j]);
}
for(int j=0; j<N; j++)
{
for(int k=0; k<Adj[j].size(); k++) //遍歷連線的結點,如果有顏色相同的,flag設為false
{
if(color[j] == color[Adj[j][k]])
{
flag = false;
break;
}
}
if(!flag) break;
}
flag ? printf("%d-coloring\n", col.size()) : printf("No\n"); //false則輸出No,true則輸出對應顏色個數
}
return 0;
}
相關文章
- PAT甲級1126~1130|C++實現C++
- PAT甲級1122 Hamiltonian Cycle (25分)|C++實現C++
- PAT甲級1110 Complete Binary Tree (25分)|C++實現C++
- (非原創)PAT甲級1123 Is It a Complete AVL Tree (30分)|C++實現C++
- 【PAT甲級A1038】Recover the Smallest Number (30分)(c++)C++
- 【PAT甲級A1084】Broken Keyboard (20分)(c++)C++
- PAT甲級1023 Have Fun with Number
- PAT 甲級 1152 Google Recruitment (20分)GoUI
- 【PAT甲級A1065】A+B and C (64bit) (20分)(c++)C++
- PAT甲級考試題庫題目分類
- 菜鳥記錄:c語言實現PAT甲級1010--RadixC語言
- PAT甲級-1005. Spell It Right (20)各位之和
- PAT甲級-1010. Radix (25)進位制
- PAT甲級-1012. The Best Rank (25)並列排序排序
- PAT乙級——1093(字串匹配)Java實現字串匹配Java
- PAT甲級-1014. Waiting in Line (30)(模擬)AI
- PAT-A Java實現Java
- 2021.9.12週六PAT甲級考試覆盤與總結
- [PAT]Table Tennis (30)Java實現Java
- PAT乙級——1092(陣列排序 自定義sort)Java實現陣列排序Java
- 【PAT乙級、C++】1024 科學計數法 (20分)C++
- 向Vertex Shader傳遞vertex attribute
- PAT1044火星數字(java實現)Java
- PAT1043 輸出PATest(java實現)Java
- PAT1048數字加密(java實現)加密Java
- B. Composite Coloring
- 【PTA甲級、C++簡單解答】1001 A+B Format (20分)C++ORM
- PAT1029 舊鍵盤(java實現)Java
- PAT1076 WiFi密碼(java實現)WiFi密碼Java
- PAT1004成績排名(java實現)Java
- [PAT]1027. Colors in Mars (20)@Java實現Java
- 【PAT乙級】1048 數字加密加密
- PAT1013數素數C++C++
- C++ 輕量級物件JSON序列化實現C++物件JSON
- PAT1019 數字黑洞(java實現)Java
- PAT1033 舊鍵盤打字(java實現)Java
- [PAT]1028. List Sorting (25)@Java實現Java
- PAT Basic 1057. 數零壹(20)(C語言實現)C語言