Codeforces Round #403 (Div. 1, based on Technocup 2017 Finals) A. Andryusha and Colored Balloons

来源:互联网 发布:怎么在淘宝上注册开店 编辑:程序博客网 时间:2024/06/05 16:51

题目分析

这道题需要求的要多少种颜色,很明显就是一个节点连接的边数最大值加一。这样再dfs进行染色,注意要保证该点与父节点和父父节点不一样,然后就可以了,不明白的直接看代码。

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxn = 2e5+100;struct Edge{    int to, next;}e[maxn<<1];int head[maxn], degree[maxn], color[maxn], tot;void addedge(int from, int to){    e[tot].to = to;    e[tot].next = head[from];    head[from] = tot++;}void dfs(int u, int fa, int ffa){    int tot = 1;    for(int i = head[u]; i != -1; i = e[i].next){        int v = e[i].to;        if(!color[v]){            if(fa == tot){                ++tot;                if(ffa == tot) ++tot;            }            if(ffa == tot){                ++tot;                if(fa == tot) ++tot;            }            color[v] = tot++;            dfs(v, color[v], color[u]);        }    }}void init(){    memset(color, 0, sizeof(color));    memset(degree, 0, sizeof(degree));    memset(head, -1, sizeof(head));    tot = 0;}int main(){    #ifdef LOCAL        freopen("input.txt", "r", stdin);    #endif // LOCAL    int n;    while(scanf("%d", &n) != EOF){        int from, to;        init();        for(int i = 1; i < n; i++){            scanf("%d%d", &from, &to);            addedge(from, to);            addedge(to, from);            degree[from]++;            degree[to]++;        }        int ans = 0, temp;        for(int i = 1; i <= n; i++)            if(degree[i]+1 > ans){                temp = i;                ans = max(ans, degree[i]+1);            }        printf("%d\n", ans);        color[temp] = 1;        dfs(temp, 1, -1);        for(int i = 1; i <= n; i++) printf("%d ", color[i]);        printf("\n");    }    return 0;}
0 0
原创粉丝点击