PAT甲級1154 Vertex Coloring (25分)|C++實現

陳xLヾ發表於2020-10-16

一、題目描述

原題連結
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;
}

相關文章