PTA: 图着色问题

题目

颜色个数必须是k个,多了少了都不行。图不一定联通。

代码

拿这个题练了一下链式向前星。

#include <cstdio>
#include <cstring>
#include <set>

using namespace std;
const int maxn = 505;
struct Edge{
    int to, next;
    Edge() {
        to = next = -1;
    }
}edge[maxn*maxn];
int head[maxn];
int tot = -1;
void add(int u, int v) {
    ++tot;
    edge[tot].to = v;
    edge[tot].next = head[u];
    head[u] = tot;
}
bool vis[maxn];
int color[maxn];
set<int> col;

bool dfs(int u) {
    if(vis[u]) return true;
    vis[u] = true;
    int i = head[u];
    while(i != -1) {
        if(color[u] == color[edge[i].to])
            return false;
        i = edge[i].next;
    }
    for(int i = head[u]; i != -1; i = edge[i].next) {
        if(!dfs(edge[i].to))
            return false;
    }
    return true;
}

int main(void)
{
    freopen("in.txt", "r", stdin);
    int v, e, k;
    scanf("%d%d%d", &v, &e, &k);
    int a, b;
    for(int i = 0; i < maxn; ++i) {
        head[i] = -1;
    }
    while(e--) {
        scanf("%d%d", &a, &b);
        add(a, b);
        add(b, a);
    }
    int n;
    scanf("%d", &n);
    while(n--) {
        memset(vis, 0, sizeof(vis));
        col.clear();
        for(int i = 1; i <= v; ++i) {
            scanf("%d", &color[i]);
            col.insert(color[i]);
        }
        if(col.size() != k) {
            puts("No");
            continue;
        }
        bool flag = true;
        for(int i = 1; i <= v; ++i) {
            if(!dfs(i)) {
                flag = false;
                break;
            }
        }
        if(flag)
            puts("Yes");
        else puts("No");
    }
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值