pat 1154

1154 Vertex Coloring (25分)

 

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

题意:给定一个图,图中每个顶点给一个颜色,要求一条边两端的顶点颜色不同。如果满足要求,输出使用的"颜色的数量-coloring",否则输出No

思路:因为图中顶点最多可以有10000个,用邻接矩阵可能会超时(笔者没试过),所以我采用的是邻接表。读入整个图的数据之后,依次遍历各条边,看两端的顶点颜色是否相同。相同则直接break输出No,否则遍历完所有顶点之后计算颜色数量输出。

代码如下:

#include<cstdio>
#include<vector>
#include<set>
using namespace std; 
vector<int> v[10005];
int n,m;
int colors[10005];
void fun(){
    int mark=0;
    for(int i=0;i<n;i++){
        for(vector<int>::iterator it=v[i].begin();it!=v[i].end();it++){
            if(colors[i]==colors[(*it)]){
                mark=1;
                break;
            }        
        }
    }
    if(mark==0){
        set<int> s;
        for(int i=0;i<n;i++){
            s.insert(colors[i]);
        }
        printf("%d-coloring
",s.size());
    }
    else
        printf("No
");
}
int main(){
    int a,b;
    scanf("%d%d",&n,&m);
    for(int i=0;i<m;i++){
        scanf("%d%d",&a,&b);
        v[a].push_back(b);
        v[b].push_back(a);
    }
    int k;
    scanf("%d",&k);
    for(int i=0;i<k;i++){
        for(int j=0;j<n;j++){
            scanf("%d",&colors[j]);
        }
        fun();
        
    }
    return 0;
}
原文地址:https://www.cnblogs.com/foodie-nils/p/13276440.html