Description
有个公司要举行一场晚会。
为了能玩得开心,公司领导决定:如果邀请了某个人,那么一定不会邀请他的上司
(上司的上司,上司的上司的上司……都可以邀请)。
每个参加晚会的人都能为晚会增添一些气氛,求一个邀请方案,使气氛值的和最大。
Input
第1行一个整数N(1<=N<=6000)表示公司的人数。
接下来N行每行一个整数。第i行的数表示第i个人的气氛值x(-128<=x<=127)。
接下来每行两个整数L,K。表示第K个人是第L个人的上司。
输入以0 0结束。
Output
一个数,最大的气氛值和。
Sample Input
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0
Sample Output
5
Source
ural 1039
【分析】
经典的树型DP。
我们这样定义状态:f[i][0]表示以i为根的子树的最大气氛值,且不选i这个节点
f[i][1]表示以i为根的子树的最大气氛值,且选i这个节点
很容易的到DP方程:
f[i][0]=sigma(max(0,f[son][0],f[son][1]));f[i][1]=sigma(max(0,f[son][0]))+max(0,v[i]);
注意边界条件:
f[i][1]=max(0,v[i]); i为叶子节点
那么答案就是:
max(f[root][0],f[root][1]);
【代码】
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int N,v[6005];
int f[6005][2],du[6005],root;
int y[6006],next[6006],last[6006],tot;
void _init()
{
scanf("%d",&N);
for(int i=1;i<=N;i++)
scanf("%d",&v[i]);
int xt,yt;
scanf("%d%d",&xt,&yt);
while(xt&&yt)
{
du[xt]++;
tot++;
y[tot]=xt;
next[tot]=last[yt];
last[yt]=tot;
scanf("%d%d",&xt,&yt);
}
}
void _DFS(int x)
{
int t0=0,t1=0;
for(int j=last[x];j;j=next[j])
{
_DFS(y[j]);
t0+=max(0,max(f[y[j]][0],f[y[j]][1]));
t1+=max(0,f[y[j]][0]);
}
f[x][0]=max(f[x][0],t0);
f[x][1]=max(f[x][1],t1+max(0,v[x]));
}
void _solve()
{
for(int i=1;i<=N;i++) //找到根节点
if(!du[i])
{
root=i;
break;
}
for(int i=1;i<=N;i++) //边界条件
if(du[i]==1)
f[i][1]=max(0,v[i]);
_DFS(root);
printf("%d\n",max(f[root][0],f[root][1]));
}
int main()
{
_init();
_solve();
return 0;
}