codeforces781A Andryusha and Colored Balloons

时间:2023-03-09 16:33:38
codeforces781A Andryusha and Colored Balloons

本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作。

本文作者:ljh2000
作者博客:http://www.cnblogs.com/ljh2000-jump/
转载请注明出处,侵权必究,保留最终解释权!

题目链接:codeforces781A Andryusha and Colored Balloons

正解:构造+结论

解题报告:

  考虑答案显然是$max(度数)+1$,这个似乎很好想,对于每个点我需要保证与之相邻的所有点颜色互不相同且与自己不同,那么需要度数$+1$种颜色,可以证明答案就是上式。

  那么我们只需要构造即可,随便找一个根$dfs$,保证每个儿子节点与当前节点和父亲节点的颜色不同即可。

//It is made by ljh2000
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <string>
#include <complex>
using namespace std;
typedef long long LL;
typedef long double LB;
typedef complex<double> C;
const double pi = acos(-1);
const int MAXN = 200011;
const int MAXM = 400011;
int n,ecnt,first[MAXN],to[MAXM],next[MAXM],d[MAXN],col[MAXN],ans;
inline void link(int x,int y){ next[++ecnt]=first[x]; first[x]=ecnt; to[ecnt]=y; }
inline int getint(){
int w=0,q=0; char c=getchar(); while((c<'0'||c>'9') && c!='-') c=getchar();
if(c=='-') q=1,c=getchar(); while (c>='0'&&c<='9') w=w*10+c-'0',c=getchar(); return q?-w:w;
} inline void dfs(int x,int fa){
int cc=0;
for(int i=first[x];i;i=next[i]) {
int v=to[i]; if(v==fa) continue;
cc++;
if(cc==col[fa]) cc++;
if(cc==col[x]) cc++;
if(cc==col[fa]) cc++;
col[v]=cc;
dfs(v,x);
}
} inline void work(){
n=getint(); int x,y;
for(int i=1;i<n;i++) {
x=getint(); y=getint();
link(x,y); link(y,x);
d[x]++; d[y]++;
}
int pos=1;
for(int i=2;i<=n;i++) if(d[i]>d[pos]) pos=i;
ans=d[pos]+1;
printf("%d\n",ans); col[1]=1;
dfs(1,0);
for(int i=1;i<=n;i++) printf("%d ",col[i]);
} int main()
{
work();
return 0;
}