Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them.
The park consists of n squares connected with (n - 1) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from 1. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if a, b and c are distinct squares that a and b have a direct path between them, and b and c have a direct path between them, then balloon colors on these three squares are distinct.
Andryusha wants to use as little different colors as possible. Help him to choose the colors!
The first line contains single integer n (3 ≤ n ≤ 2·105) — the number of squares in the park.
Each of the next (n - 1) lines contains two integers x and y (1 ≤ x, y ≤ n) — the indices of two squares directly connected by a path.
It is guaranteed that any square is reachable from any other using the paths.
In the first line print single integer k — the minimum number of colors Andryusha has to use.
In the second line print n integers, the i-th of them should be equal to the balloon color on the i-th square. Each of these numbers should be within range from 1 to k.
3 2 3 1 3
3 1 3 2
思路:树,想着用分层搜索的方式,开始想着用bfs,每个点的颜色是除之前搜索过两层颜色外同层中最小可以获取的
颜色。后来觉得bfs记录的东西太多,用dfs代替,新思路是当前节点颜色是除父亲节的,祖父节点颜色外,
当前深度(树的深度,其实也是层次)下最小可以获取的颜色。但比赛时候提交wa了,后来想明白了,
不能是当前深度,应该是同一父亲节点的当前深度,否则公共祖先不是父亲节点颜色是没有要求的,按照
要求处理就会错。
总之最终思路:新思路是当前节点颜色是除父亲节,祖父节点颜色外,当前节点的父节点下的当前未使用颜色的
最小值。
代码有注释,看一下就懂了:
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
const int N = 200010;
using namespace std;
typedef long long ll;
int ans, n;
int color[N];
int cid[N];//记录当前节点的儿子中最小可以使用的颜色值
vector<int> G[N];
void dfs(int u, int fa, int ffa)
{
int fcol = 0, ffcol = 0;
if (fa != 0)
fcol = color[fa];
if (ffa != 0)
ffcol = color[ffa];
if (cid[fa] == 0)
cid[fa]++;
if (cid[fa] == fcol)
cid[fa]++;
if (cid[fa] == ffcol)
cid[fa]++;
if (cid[fa] == fcol)//多写一遍,因为存在祖父节点颜色加1又跟父节点颜色冲突的情况
cid[fa]++;
color[u] = cid[fa];
ans = max(ans, cid[fa]);
cid[fa]++;
for (int i = 0; i < G[u].size(); i++)
{
int v = G[u][i];
if (v != fa)
dfs(v, u, fa);
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r" ,stdin);
#endif
while (~scanf("%d", &n))
{
memset(cid, 0, sizeof(cid));
ans = 0;
for (int i = 1; i <= n; i++)G[i].clear();
for (int i = 1; i < n; i++)
{
int a, b;
scanf("%d%d", &a, &b);
G[a].push_back(b);
G[b].push_back(a);
}
dfs(1, 0, 0);
printf("%d\n", ans);
for (int i = 1; i <= n; i++)
printf("%d%c", color[i], i == n? '\n': ' ');
}
return 0;
}