C. Andryusha and Colored Balloons
Description
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!
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.
题意
给定一 n 个点,n-1 条双向边的树,要求给树上每个节点染色,若 a 与 b 直接相连,b 与 c 直接相连,则 a, b, c 三点的颜色不能相同。问最少需要用多少种颜色(颜色从 1 开始编号)?且需输出每个点的颜色。
分析
根据 ” a 与 b 直接相连,b 与 c 直接相连,则 a, b, c 三点的颜色不能相同“ 的规则。可知与点 x 直接相连的若干点均与 x 颜色不同,且其各自颜色不同。
通过简单深搜可解决这一问题。对于每个点,标记与其相连的点已经使用的颜色,对于与其相连且未标记的点,从 1 开始进行遍历,找到最小的未使用的颜色标号对其进行标记。一层层深搜即可。
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+10;
vector<int> g[N];
int color[N], mx;
map<pair<int, int>, bool> mp;
void dfs(int rt, int fa)
{
for(int i=0, to;i<g[rt].size();i++) //对点 rt 的各个子节点标记已经使用过的颜色,即 color[rt]
{
to = g[rt][i];
if(to == fa) continue;
mp[make_pair(to, color[rt])] = true;
}
int idx = 1;
for(int i=0, to;i<g[rt].size();i++) //点 rt 对其未染色的子节点进行染色
{
to = g[rt][i];
if(to == fa) continue;
while(idx == color[rt] || mp[make_pair(rt, idx)] == true) idx++;
mx = max(mx, idx);
color[to] = idx++;
dfs(to, rt);
}
}
int main()
{
int n;
scanf("%d",&n);
for(int i=1, u, v;i<n;i++)
scanf("%d %d",&u,&v),
g[u].push_back(v),
g[v].push_back(u);
color[1] = 1;
dfs(1, -1);
printf("%d\n",mx);
for(int i=1;i<=n;i++)
printf("%d ",color[i]);
}