Codeforces Round #411 (Div. 2) E - Ice cream coloring

E - Ice cream coloring

题意:

​ 有一棵树T,节点为1~n,现在有m种ice cream,每一个节点都有si种ice cream,现在新建一棵树G,节点为ice cream 的种类数,标号为1~m,边是否相连有如下规则:

​ if and only if there exists a vertex in T that has both the v-th and the u-th types of ice cream in its set.

在原树T中同时存在于一个节点的ice cream互相连接,比如1 节点中有3种ice cream那么这三种ice cream互相存在边,也就是一个完全图。

​ 要求:求出新建的G图中,要把所有的点都染色,相邻的点不能有相同的颜色,最少需要多少种颜色,输出最少的颜色个数和每一个点染色的颜色标号(从1开始),并且尽量下标小。

思路:

​ 对于原树中存在于同一个点的ice cream种类数直接给出从小到大的标记,需要处理的问题是如果解决已经染过色的节点,方法:

​ 保存当前节点u中已经被染色的ice cream染的哪一种颜色的标记,然后排序,从颜色1开始染未曾染色的ice cream,需要跳过已经用过的颜色。(细节处理,代码细细思考。)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <set>

using namespace std;

const int maxn = 3*1e5+10;

int n,m;
set<int>ice[maxn];
set<int>::iterator it;
vector<int>edge[maxn];
int cnt,ans[maxn];

void dfs(int u,int fa)
{
    if(fa == -1) {
        for(it = ice[u].begin();it != ice[u].end(); it++) {
            ans[(*it)] = ++cnt;
        }
    }
    else {
        vector<int>used;
        for(it = ice[u].begin();it != ice[u].end(); it++) {
            if(ans[(*it)]) {
                used.push_back(ans[(*it)]);
            }
        }
        int L = used.size();
        int now = 1,pos = 0;
        sort(used.begin(),used.end());
        for(it = ice[u].begin();it != ice[u].end(); it++) {
            if(!ans[(*it)]) {
                while(pos < L) {
                    if(used[pos] == now) now++,pos++;
                    else break;
                }
                ans[(*it)] = now++;
            }
            cnt = max(cnt,now-1);
        }
    }
    int Size = edge[u].size();
    for(int i = 0;i < Size; i++) {
        int to = edge[u][i];
        if(to != fa)
            dfs(to,u);
    }
}

int main()
{
//    freopen("in.txt","r",stdin);

    scanf("%d%d",&n,&m);
    for(int i = 1;i <= n; i++) {
        int temp;
        scanf("%d",&temp);
        for(int j = 1;j <= temp; j++) {
            int cream;
            scanf("%d",&cream);
            ice[i].insert(cream);
        }
    }
    for(int i = 1;i < n; i++) {
        int u,v;
        scanf("%d%d",&u,&v);
        edge[u].push_back(v);
        edge[v].push_back(u);
    }
    cnt = 0;
    dfs(1,-1);
    if(cnt == 0) cnt = 1;
    printf("%d\n",cnt);
    for(int i = 1;i <= m; i++) {
        if(i != m) printf("%d ",ans[i]?ans[i]:1);
        else printf("%d\n",ans[i]?ans[i]:1);
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值