Codeforces Round #411 (Div. 2) E

来源:互联网 发布:weibull 7软件下载 编辑:程序博客网 时间:2024/06/05 02:47

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;}
原创粉丝点击