3631: [JLOI2014]松鼠的新家
Time Limit: 10 Sec Memory Limit: 128 MB Submit: 2560 Solved: 1357 [ ][ ][ ]Description
松鼠的新家是一棵树,前几天刚刚装修了新家,新家有n个房间,并且有n-1根树枝连接,每个房间都可以相互到达,且俩个房间之间的路线都是唯一的。天哪,他居然真的住在“树”上。松鼠想邀请小熊维尼前来参观,并且还指定一份参观指南,他希望维尼能够按照他的指南顺序,先去a1,再去a2,……,最后到an,去参观新家。可是这样会导致维尼重复走很多房间,懒惰的维尼不听地推辞。可是松鼠告诉他,每走到一个房间,他就可以从房间拿一块糖果吃。维尼是个馋家伙,立马就答应了。现在松鼠希望知道为了保证维尼有糖果吃,他需要在每一个房间各放至少多少个糖果。因为松鼠参观指南上的最后一个房间an是餐厅,餐厅里他准备了丰盛的大餐,所以当维尼在参观的最后到达餐厅时就不需要再拿糖果吃了。Input
第一行一个整数n,表示房间个数第二行n个整数,依次描述a1-an接下来n-1行,每行两个整数x,y,表示标号x和y的两个房间之间有树枝相连。Output
一共n行,第i行输出标号为i的房间至少需要放多少个糖果,才能让维尼有糖果吃。Sample Input
5
1 4 5 3 2
1 2
2 4
2 3
4 5
Sample Output
1
2
1
2
1
HINT
2<= n <=300000
题目大意:给定一棵n个节点的树和一个1~n的排列ai,对于每一个i,给从ai到ai+1的路径上除了起点以外的点都加上1,求每个点最终的值
题解:
看到题就感觉像树剖,于是就直接套板子上了。每次对于一条链来说,给左端点加上1,右端点的下一位减去1,最后做一个前缀和。注意每次是不给起点+1的,因此最后给除了a1以外的点全部-1就好了
代码:
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #include 10 #include 11 #include 12 #include 13 #include 14 #include 15 #include 16 #include 17 #include 18 #include 19 #include 20 #include 21 #include 22 #include 23 #include 24 #include 25 #include 26 #include 27 #include 28 #include 29 #include 30 #include 31 #include 32 #include 33 #include 34 #include 35 #include 36 #include
37 #include
然后就发现自己做烦了。
我都想到了给左端点加1右端点减1了,就没想到树上也能这样做
每次操作,给两个端点都加上1,然后给他们的lca减去1,lca的父亲也减去1,然后在dfs一下,每个点的权值加上他的儿子们的权值。注意,输出时所有的点的权值-1,原因同上
代码:
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #include 10 #include 11 #include 12 #include 13 #include 14 #include 15 #include 16 #include 17 #include 18 #include 19 #include 20 #include 21 #include 22 #include 23 #include 24 #include 25 #include 26 #include 27 #include 28 #include 29 #include 30 #include 31 #include 32 #include 33 #include 34 #include 35 #include 36 #include
37 #include