当前位置:首页 > 动态规划 > 树形DP > 正文
[没有上司的舞会]POJ2342AnniversaryParty
3466+

题目大意:已知n个人的上下级关系,现在需要办一个没有直接上司的晚会,让所有员工都玩得开心, 请问最多有多少人可以参加?[CODEVS1380、HDU1520]

Description

There is going to be a party to celebrate the 80-th Anniversary of the Ural State University. The University has a hierarchical structure of employees. It means that the supervisor relation forms a tree rooted at the rector V. E. Tretyakov. In order to make the party funny for every one, the rector does not want both an employee and his or her immediate supervisor to be present. The personnel office has evaluated conviviality of each employee, so everyone has some number (rating) attached to him or her. Your task is to make a list of guests with the maximal possible sum of guests’ conviviality ratings.

Input

Employees are numbered from 1 to N. A first line of input contains a number N. 1 <= N <= 6 000. Each of the subsequent N lines contains the conviviality rating of the corresponding employee. Conviviality rating is an integer number in a range from -128 to 127. After that go N – 1 lines that describe a supervisor relation tree. Each line of the tree specification has the form:
L K
It means that the K-th employee is an immediate supervisor of the L-th employee. Input is ended with the line
0 0

Output

Output should contain the maximal sum of guests’ ratings.

Sample Input

7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0

Sample Output

5

解题思路

上下级关系是一棵树,现在需要从树中选最多的结点,且要求任意两个结点不能存在父子关系,也就是说,选了父亲,就不能选儿子,选了儿子,就不能选父亲。

我们可以考虑在树上面做动态规划,即树形动规。对于每个结点,要么选,要么不选。f[i]表示选i这个结点,i这棵子树最多有多少人参加晚会;g[i]表示不选i这个结点,i这棵子树最多有多少人参加晚会。那么对于根结点a,每一个儿子结点b,f[a] += g[b],因为a去了,b就不能去;g[a] += max(f[b], g[b]),因为a不去,b可以去,也可以不去。

如果a是b的上司,那么a到b建立一条有向边;由于题目没有说明谁是最高级别的,我们需要找入度为0的点,从它开始搜索整棵子树;为了避免有多少入度为0的点,我们可以建立一个超级树根m,指向所有入度为0的点;在搜索过程中,儿子结点搜索完后,才会确定儿子所在子树的最多参加人数,才能更新父亲结点的信息;最终答案是g[m],因为m是不存在的,不会参加晚会。

程序实现

About

坚决不Copy代码!

本文标签:,,,

[没有上司的舞会]POJ2342AnniversaryParty:等您坐沙发呢!

发表评论

您必须 [ 登录 ] 才能发表留言!