Luogu P1352 没有上司的舞会 (树形DP)

题目

题目描述

某大学有N个职员,编号为1~N。他们之间有从属关系,也就是说他们的关系就像一棵以校长为根的树,父结点就是子结点的直接上司。现在有个周年庆宴会,宴会每邀请来一个职员都会增加一定的快乐指数Ri,但是呢,如果某个职员的上司来参加舞会了,那么这个职员就无论如何也不肯来参加舞会了。所以,请你编程计算,邀请哪些职员可以使快乐指数最大,求最大的快乐指数。

输入输出格式

输入格式:

第一行一个整数N。(1<=N<=6000)

接下来N行,第i+1行表示i号职员的快乐指数Ri。(-128<=Ri<=127)

接下来N-1行,每行输入一对整数L,K。表示KL的直接上司。

最后一行输入0 0

输出格式:

输出最大的快乐指数。

输入输出样例

输入样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0

输出样例:

1
5

题解

划水这么久终于把这道树形DP入门题给做了。。。

dp[staff][0]表示staff不去得到的最大值,dp[staff][1]表示去了得到的最大值

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <bits/stdc++.h>
using namespace std;
vector<int> subordinate[6010];
int dp[6010][2];
int n, is_chairman[6010], chairman;
inline void Dfs(const int staff) {
if (!subordinate[staff].size()) return;
for (register int i(0), subnum(subordinate[staff].size()); i < subnum; ++i) {
Dfs(subordinate[staff][i]);
dp[staff][1] = max(max(dp[staff][1],
dp[subordinate[staff][i]][0] + dp[staff][1]),
dp[subordinate[staff][i]][0]);
dp[staff][0] = max(max(dp[staff][0],
dp[subordinate[staff][i]][1] + dp[staff][0]),
max(dp[subordinate[staff][i]][1],
dp[subordinate[staff][i]][0]));
}
}
int main(int argc, char **argv) {
scanf("%d", &n);
fill(is_chairman, is_chairman + n + 10, 1);
for (register int i(1); i <= n; ++i) {
scanf("%d", &dp[i][1]);
}
for (register int i(1), staff, boss; i < n; ++i) {
scanf("%d %d", &staff, &boss);
subordinate[boss].push_back(staff);
is_chairman[staff] = 0;
}
for (register int i(1); i <= n; ++i) {
if (is_chairman[i]) {
chairman = i;
break;
}
}
Dfs(chairman);
printf("%d\n", max(dp[chairman][0], dp[chairman][1]));
return 0;
}