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]));//論根節點選好還是不選好
}