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
5
2 3
5 3
4 3
1 3
5
1 3 2 5 4
5
2 1
3 2
4 3
5 4
3
1 2 3 1 2
题意:有n个节点,有n-1条边并且保证全部联通(是一棵生成树),相连的三个节点不能同色,例如A与B相连,B与C相连,那么ABC不能同色,输出颜色的最小种类和一种解决方案。
#include <iostream> #include <stdio.h> #include <string.h> #include <vector> #include <math.h> #include <algorithm> using namespace std; vector<int> v[200010]; int k=0; int ans[200010]; void dfs(int x,int q) { int d=1; for(int i=0;i<v[x].size();i++) { if(ans[v[x][i]]==0) { while(d==ans[x]||d==ans[q]) d++; ans[v[x][i]]=d++; k=max(ans[v[x][i]],k); dfs(v[x][i],x); } } } int main() { int n,i,j,a,b; scanf("%d",&n); for(i=0; i<n-1; i++) { scanf("%d%d",&a,&b); v[a].push_back(b); v[b].push_back(a); } ans[1]=1; dfs(1,0); printf("%d ",k); for(i=1;i<=n;i++) { if(i!=1) printf(" %d",ans[i]); if(i==1) printf("%d",ans[i]); } return 0; }
解析:利用vector开辟动态数组,储存每个点互相链接的点,从1开始dfs遍历,并且传两个参数x,q,前者代表当前遍历的点,后者代表前一个的点,只要参考这两个点就能找的第三点的颜色。