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;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/109126677