PTA groups Programming Ladder Race - Practice set L2-023 graph coloring problem (25 points)

Graph coloring problem is a well-known NP-complete problem. Given an undirected graph G = (V, E), and asked whether the K colors assigned a color of each vertex of the V such that no two adjacent vertices with the same color?

But this problem is not to solve the problem of coloring you, but given a color assignment, you determine whether this is a solution graph coloring problem.

Input formats:

Input gives three integers V (0 <V≤500) in the first row, E (≥0) and K (0 <K≤V), the number of vertices are undirected graph, the number of edges, and the number of colors. Vertex and colors are numbered from 1 to V. Then E lines of a given number of sides of the two end points. After the information is given in FIG gives a positive integer N (≤20), is the number of color assignment scheme to be examined. Then N rows, each row is sequentially given color vertex V (i-th digit denotes the i th vertex color), separated by spaces between digits. Title ensure that a given directed graph is not legitimate (i.e., from the circuit and there is no side weight)

Output formats:

For each color allocation, graph coloring problem is if a solution is output Yes, otherwise the output No, each sentence per line.

Sample input:

6 8 3
2 1
1 3
4 6
2 5
2 4
5 4
5 6
3 6
4
1 2 3 3 1 2
4 5 6 6 4 5
1 2 3 4 5 6
2 3 4 2 3 4

Sample output:

Yes
Yes
No
No
注意几个测试点:
    1. 颜色的种类可能不是k个
    2. 有的样例给的无向图不是全连通图,存在分块
#include<cstdio>
#include<iostream>
#include<cstring>
#include<set>
using namespace std;
const int N = 510;
int h[N],ne[N*N],e[N*N],colors[N],idx;
int v,edge,k,x,y;
set<int> color_category;

void add(int x,int y){
    e[idx] = y;
    ne[idx] =  h[x];
    h[x] = idx++;
}

bool check(){
    for (int i = 1; i <= v; ++i){
        color_category.insert(colors[i]);
        int node;
        for (int t = h[i];t != -1; t = ne[t]){
            node = e[t];
            if (colors[node] == colors[i] || colors[node] > v || colors[node] <= 0)
                return false;
        }
    }
    if (color_category.size() != k) return false;
    return true;
}

int main(){
    memset(h,-1,sizeof h);
    scanf("%d%d%d",&v,&edge,&k);
    for (int i = 0; i < edge; ++i){
        scanf("%d%d",&x,&y);
        add(x,y),add(y,x);
    }
    int test_k;
    scanf("%d",&test_k);
    while(test_k--){
        color_category.clear();
        for (int i = 1; i <= v; ++i){
            scanf("%d",&colors[i]);
        }
        if (check())
            puts("Yes");
        else puts("No");
    }
    return 0;
}

 

 

Published 349 original articles · won praise 32 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_41514525/article/details/104089755