#树上DFS# Codeforces Round #403 (Div. 2) C. Andryusha and Colored Balloons

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值