CF781A Andryusha and Colored Balloons

本文探讨了一道有趣的搜索问题——给一棵无根树染色,使得相邻的三个节点颜色不同,目标是最少使用多少种颜色。通过深度优先搜索算法进行解决,并给出了完整的C++实现代码。

题意:

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 ab and c are distinct squares that aand 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!

Input

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.

Output

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.

Examples
input
3
2 3
1 3
output
3
1 3 2
input
5
2 3
5 3
4 3
1 3
output
5
1 3 2 5 4
input
5
2 1
3 2
4 3
5 4
output
3
1 2 3 1 2

大意是说给一棵无根树染色,相邻的三个节点颜色不能相同,问至少需要多少种颜色。

思路:

有趣的搜索。

实现:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <vector>
 4 using namespace std;
 5 
 6 vector<int> G[200005];
 7 int color[200005];
 8 int ans = 1;
 9 void dfs(int now, int f)
10 {
11     int x = 0;
12     for (int i = 0; i < G[now].size(); i++)
13     {
14         if (G[now][i] == f || color[G[now][i]])
15             continue;
16         x++;
17         while (x == color[now] || x == color[f])
18             x++;
19         color[G[now][i]] = x;
20         dfs(G[now][i], now);
21     }
22     if (x > ans)
23         ans = x;
24 }
25 int n, x, y;
26 int main()
27 {
28     cin >> n;
29     for (int i = 1; i <= n - 1; i++)
30     {
31         cin >> x >> y;
32         G[x].push_back(y);
33         G[y].push_back(x);
34     }
35     color[1] = 1;
36     dfs(1, 0);
37     cout << ans << endl;
38     for (int i = 1; i <= n; i++)
39     {
40         cout << color[i] << " ";
41     }
42     cout << endl;
43     return 0;
44 }

 

转载于:https://www.cnblogs.com/wangyiming/p/6516551.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值