题意:
给一棵树,用最少的颜色上色,使得任意满足a连接b,b连接c,的三点颜色不同,打印颜色种类,及每个点的上色方案。
思路:
好在数据的结构是树,所以连续的三个点的关系只可能是 父节点-节点-子节点 或 子节点-节点-子节点。
在分配颜色时,只用先考虑 父节点-节点 的颜色关系,再逐个分配子节点的颜色即可。
故可 从任意节点开始 bfs 遍历树并记录节点颜色和父节点颜色。
若题目改为 连续4点颜色不同 要考虑的节点关系和其颜色限制就非常麻烦。
若题目改为 图 结构 则可参考 四色定理 。
代码:
#include <bits/stdc++.h>
using namespace std;
const int MAXN=2e5+100;
int n,x,y,pos;
vector <int> mp[MAXN];
int color[MAXN],fcolor[MAXN],co,now,ans;
void solve(){
memset(color,0,sizeof(color));
ans=1;
queue <int> que;
que.push(1);
fcolor[1]=color[1]=1;
while(!que.empty()){
co=1;
pos=que.front();
que.pop();
for(int i=0;i<mp[pos].size();i++){
now=mp[pos][i];
if(!color[now]){
fcolor[now]=color[pos];
while(co==color[pos]||co==fcolor[pos]) co++;
color[now]=co;co++;
que.push(now);
}
}
ans=max(ans,co-1);
}
}
void opt(){
cout<<ans<<endl;
for(int i=1;i<=n;i++){
mp[i].clear();
cout<<color[i];
if(i==n) cout<<endl;
else cout<<' ';
}
}
int main()
{
ios::sync_with_stdio(false);
while(cin>>n){
for(int i=0;i<n-1;i++){
cin>>x>>y;
mp[x].push_back(y);
mp[y].push_back(x);
}
solve();
opt();
}
}
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
In the first sample the park consists of three squares: 1 → 3 → 2. Thus, the balloon colors have to be distinct.
In the second example there are following triples of consequently connected squares:
- 1 → 3 → 2
- 1 → 3 → 4
- 1 → 3 → 5
- 2 → 3 → 4
- 2 → 3 → 5
- 4 → 3 → 5
In the third example there are following triples:
- 1 → 2 → 3
- 2 → 3 → 4
- 3 → 4 → 5