Codeforces Round #403 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 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!
题目大意:
给一棵树,用最少的颜色上色,使得任意满足a连接b,b连接c,的三点颜色不同,打印颜色种类,及每个点的上色方案
解题思路:
树上DFS的模板题
一个学长的代码,由于这个代码刚好深得我心就直接拿来用了:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<iostream>
using namespace std;
const int MaxN = 2e5 + 5;
int cnt[MaxN];
int pre[2 * MaxN], last[MaxN], other[2 * MaxN];
int all, ans, n;
int color[MaxN];
void init(){
memset(pre, 0, sizeof(pre));
memset(last, -1, sizeof(last));
memset(other, 0, sizeof(other));
memset(color, 0, sizeof(color));
memset(cnt, 0, sizeof(cnt));
ans = 0;
all = -1;
}
void build(int u, int v){
pre[++all] = last[u]; //由u节点出发的当前边的前一条边
last[u] = all; //u节点最后连出的边
other[all] = v; //当前边指向的节点(v)
}
void Dfs(int x, int fa){
int pos = 1; //当前节点的颜色
int ed = last[x], dr; //ed:u节点最后连出的边
while(ed != -1){
dr = other[ed]; //dr:u节点最后连出的边所指向的节点
if(dr != fa){
while(pos == color[x] || pos == color[fa]) pos++;
color[dr] = pos++;
Dfs(dr, x);
}
ed = pre[ed]; //由当前节点最后发出的边的 前一条 由当前节点发出的边
}
}
int main(){
while(~scanf("%d", &n)) {
init();
for(int i = 1; i < n; i++){
int u, v;
scanf("%d %d", &u, &v);
cnt[u]++; cnt[v]++;
ans = max(ans, max(cnt[u], cnt[v])); //ans用来存最少颜色数
build(u, v);
build(v, u);
}
color[1] = 1;
Dfs(1, 0);
printf("%d\n", ans + 1);
for(int i = 1; i <= n; i++) printf("%d ", color[i]);
printf("\n");
}
return 0;
}