团体天梯练习 L2-023 图着色问题

L2-023 图着色问题

图着色问题是一个著名的 \(NP\) 完全问题。给定无向图 \(G = (V, E)\) ,问可否用 \(K\) 种颜色为 \(V\) 中的每一个顶点分配一种颜色,使得不会有两个相邻顶点具有同一种颜色?

但本题并不是要你解决这个着色问题,而是对给定的一种颜色分配,请你判断这是否是图着色问题的一个解。

输入格式:

输入在第一行给出3个整数 \(V\)\(0<V≤500\) )、\(E\)\(≥0\) )和 \(K\)\(0<K≤V\) ),分别是无向图的顶点数、边数、以及颜色数。顶点和颜色都从 \(1\)\(V\) 编号。随后 \(E\) 行,每行给出一条边的两个端点的编号。在图的信息给出之后,给出了一个正整数 \(N\)\(≤20\) ),是待检查的颜色分配方案的个数。随后 \(N\) 行,每行顺次给出 \(V\) 个顶点的颜色(第 \(i\) 个数字表示第 \(i\) 个顶点的颜色),数字间以空格分隔。题目保证给定的无向图是合法的(即不存在自回路和重边)。

输出格式:

对每种颜色分配方案,如果是图着色问题的一个解则输出 \(Yes\) ,否则输出 \(No\) ,每句占一行。

输入样例:

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

输出样例:

Yes
Yes
No
No


解题思路

这道题点的个数小于等于 \(500\),边的条数为 \(N^{2}\) 量级,所以暴力判断每一条边相连的两个点是否存在颜色相同即可。不过题目要求必须染成 \(k\) 种颜色,所以需要事先判断每条询问是否满足 \(k\) 种颜色。

/*   一切都是命运石之门的选择  El Psy Kongroo  */
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<cmath>
#include<functional>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef pair<double, double> pdd;
typedef pair<string, int> psi;
typedef __int128 int128;
#define PI acos(-1.0)
#define x first
#define y second
//int dx[4] = {1, -1, 0, 0};
//int dy[4] = {0, 0, 1, -1};
const int inf = 0x3f3f3f3f, mod = 1e9 + 7;


const int N = 510, M = N * N;
int h[N], e[M], ne[M], idx;
int n, m, k;
int color[N];

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

//暴力判断每个边即可
bool check(){
    for(int u = 1; u <= n; u ++ )
        for(int i = h[u]; ~i; i = ne[i]){
            int v = e[i], c = color[v];
            if(c == color[u]) return false;
        }
    return true;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    memset(h, -1, sizeof(h));
    cin >> n >> m >> k;
    while(m -- ){
        int u, v; cin >> u >> v;
        add(u, v), add(v, u);
    }

    int q; cin >> q;
    while(q -- ){
        set<int> st;
        for(int i = 1; i <= n; i ++ ){
            int x; cin >> x;
            color[i] = x;
            st.insert(x);
        }

        if((int)st.size() != k){    //不符合染成k中颜色的要求
            cout << "No" << endl;
            continue;
        }

        bool res = check();
        if(res) cout << "Yes" << endl;
        else cout << "No" << endl;
    }

    return 0;
}
posted @ 2023-04-18 16:53  MarisaMagic  阅读(32)  评论(0编辑  收藏  举报