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

LinkLink

SSLOJSSLOJ 16071607

DescriptionDescription

Ural大学有N个职员,编号为1~N。他们有从属关系,也就是说他们的关系就像一棵以校长为根的树,父结点就是子结点的直接上司。每个职员有一个快乐指数。现在有个周年庆宴会,要求与会职员的快乐指数最大。但是,没有职员愿和直接上司一起与会。

InputInput

第一行一个整数N。(1<=N<=6000)
接下来N行,第i+1行表示i号职员的快乐指数Ri。(-128<=Ri<=127)
接下来N-1行,每行输入一对整数L,K。表示K是L的直接上司。
最后一行输入0,0。(其实根本不用读的。。。)

OutputOutput

输出最大的快乐指数。

SampleSample InputInput

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

SampleSample OutputOutput

5

TrainTrain ofof ThoughtThought

树形DP
动态转移方程:
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[dep][1]+=f[tree[i].to][0]f[dep][1] += f[tree[i].to][0]
其中depdep为当前节点编号,treetree为建的树

CodeCode

#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]));//论根节点选好还是不选好
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章