Description
Ural大学有N个职员,编号为1~N。他们有从属关系,也就是说他们的关系就像一棵以校长为根的树,父结点就是子结点的直接上司。每个职员有一个快乐指数。现在有个周年庆宴会,要求与会职员的快乐指数最大。但是,没有职员愿和直接上司一起与会。
Input
第一行一个整数N。(1<=N<=6000)
接下来N行,第i+1行表示i号职员的快乐指数Ri。(-128<=Ri<=127)
接下来N-1行,每行输入一对整数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
思路:
我们先可以分析,假如选了 i i i这个点,那么和它相邻的点都不能选。那我们就设两个状态,分别为选或不选这个点,那么动态转移方程为
f [ x ] [ 1 ] + = f [ y ] [ 0 ] f[x][1]+=f[y][0] f[x][1]+=f[y][0]
f [ x ] [ 0 ] + = m a x ( f [ y ] [ 1 ] , f [ y ] [ 0 ] ) f[x][0]+=max(f[y][1], f[y][0]) f[x][0]+=max(f[y][1],f[y][0])
其中 x x x代表当前的点, y y y代表它的相邻点
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
int n, a[100100], ot[100100];
int head[100100], tot;
int f[100100][2];
struct node{
int to, next;
}b[1000100];
void VL_ljb(int x, int y)
{
b[++tot]=(node){y, head[x]};
head[x]=tot;
}
void VL_dp(int x)
{
f[x][1]=a[x];
for(int i=head[x]; i; i=b[i].next)
{
int y=b[i].to;
VL_dp(y);
f[x][1]+=f[y][0];
f[x][0]+=max(f[y][1], f[y][0]);
}
}
int main()
{
scanf("%d", &n);
for(int i=1; i<=n; i++) scanf("%d", &a[i]);
int x, y;
scanf("%d%d", &x, &y);
while(x&&y)
{
VL_ljb(y ,x);
ot[x]++;
scanf("%d%d", &x, &y);
}
int k=0;
for(int i=1; i<=n; i++)
{
if(ot[i]==0)
{
k=i;
VL_dp(i);
break;
}
}
printf("%d", max(f[k][1],f[k][0]));
return 0;
}