【树形DP】SSLOJ 1607 没有上司的晚会

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]));//论根节点选好还是不选好
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值