L i n k Link Link
S S L O J SSLOJ SSLOJ 1607 1607 1607
D e s c r i p t i o n Description Description
Ural大学有N个职员,编号为1~N。他们有从属关系,也就是说他们的关系就像一棵以校长为根的树,父结点就是子结点的直接上司。每个职员有一个快乐指数。现在有个周年庆宴会,要求与会职员的快乐指数最大。但是,没有职员愿和直接上司一起与会。
I n p u t Input Input
第一行一个整数N。(1<=N<=6000)
接下来N行,第i+1行表示i号职员的快乐指数Ri。(-128<=Ri<=127)
接下来N-1行,每行输入一对整数L,K。表示K是L的直接上司。
最后一行输入0,0。(其实根本不用读的。。。)
O u t p u t Output Output
输出最大的快乐指数。
S a m p l e Sample Sample I n p u t Input Input
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0
S a m p l e Sample Sample O u t p u t Output Output
5
T r a i n Train Train o f of of T h o u g h t Thought Thought
树形DP
动态转移方程:
f
[
d
e
p
]
[
0
]
+
=
m
a
x
(
f
[
t
r
e
e
[
i
]
.
t
o
]
[
0
]
,
f
[
t
r
e
e
[
i
]
.
t
o
]
[
1
]
)
f[dep][0] += max(f[tree[i].to][0], f[tree[i].to][1])
f[dep][0]+=max(f[tree[i].to][0],f[tree[i].to][1])
f
[
d
e
p
]
[
1
]
+
=
f
[
t
r
e
e
[
i
]
.
t
o
]
[
0
]
f[dep][1] += f[tree[i].to][0]
f[dep][1]+=f[tree[i].to][0]
其中
d
e
p
dep
dep为当前节点编号,
t
r
e
e
tree
tree为建的树
C o d e Code Code
#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]));//论根节点选好还是不选好
}