Ural大学有N个职员,编号为1~N。他们有从属关系,也就是说他们的关系就像一棵以校长为根的树,父结点就是子结点的直接上司。每个职员有一个快乐指数。现在有个周年庆宴会,要求与会职员的快乐指数最大。但是,没有职员愿和直接上司一起与会。
第一行一个整数N。(1<=N<=6000)
接下来N行,第i+1行表示i号职员的快乐指数Ri。(-128<=Ri<=127)
接下来N-1行,每行输入一对整数L,K。表示K是L的直接上司。
最后一行输入0,0。(其实根本不用读的。。。)
输出最大的快乐指数。
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0
5
树形DP
动态转移方程:
其中为当前节点编号,为建的树
#include<iostream>
#include<cstdio>
using namespace std;
int t, n, father; bool Son[6005];
int h[6005], f[6005][2], Happy[6005];
struct Tree
{
int to, next;
}tree[15005];
void dp(int dep)
{
f[dep][1] = Happy[dep];
for (int i = h[dep]; i; i = tree[i].next)
{
dp(tree[i].to);
f[dep][0] += max(f[tree[i].to][0], f[tree[i].to][1]);
f[dep][1] += f[tree[i].to][0];//动态转移方程
}
}
int main()
{
int x, y;
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
scanf("%d",&Happy[i]);
for (int i = 1; i <= n - 1; ++i)
{
scanf("%d%d", &x, &y);
tree[++t] = (Tree){x, h[y]}; h[y] = t;//建树
Son[x] = true;
}
for (int i = 1; i <= n; ++i)
if (!Son[i]) father = i;//找出根节点
dp(father);
printf("%d", max(f[father][0], f[father][1]));//论根节点选好还是不选好
}