1154 Vertex Coloring (25 point(s))

思路:

利用广度优先搜索 BFS,匹配节点与附近节点颜色是否不一样,同时需要考虑非连通图的情况,颜色的数量可以用 set 记录。

1154 Vertex Coloring (25 point(s))

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.

Example:

#include<iostream>
#include<vector>
#include<queue>
#include<set>
using namespace std;

struct Graph {
    int Nv;
    int Ne;
    vector<set<int>> G;
};

int coloring(Graph &G, vector<int> &color)
{
    set<int> mark;
    queue<int> Q;
    vector<bool> visited(G.Nv, false);
    for(int i = 0; i < G.Nv; i++) {
        if(!visited[i]) {
            Q.push(i);
            mark.insert(color[i]);
            visited[i] = true;
            while(!Q.empty()) {
                int front = Q.front();
                for(auto &x : G.G[front]) {
                    if(color[x] == color[front]) return 0;
                    if(!visited[x]) {
                        Q.push(x);
                        visited[x] = true;
                        mark.insert(color[x]);
                    }
                }
                Q.pop();
            }
        }
    }
    return mark.size();
}

int main()
{
    int N, M, K;
    cin >> N >> M;
    Graph G;
    G.Nv = N, G.Ne = M, G.G.resize(N);
    for(int i = 0; i < M; i++) {
        int v1, v2;
        cin >> v1 >> v2;
        G.G[v1].insert(v2);
        G.G[v2].insert(v1);
    }
    cin >> K;
    vector<int> color(N);
    for(int i = 0; i < K; i++) {
        for(int j = 0; j < N; j++) cin >> color[j];
        int result = coloring(G, color);
        if(result > 0) printf("%d-coloring\n", result);
        else cout << "No\n";
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值