问题描述
有一棵 n 个节点的树,树上每个节点都有一个正整数权值。如果一个点被选择了,那么在树上和它相邻的点都不能被选择。求选出的点的权值和最大是多少?
输入格式
第一行包含一个整数 n 。
接下来的一行包含 n 个正整数,第 i 个正整数代表点 i 的权值。
接下来一共 n-1 行,每行描述树上的一条边。
输出格式
输出一个整数,代表选出的点的权值和的最大值。
样例输入
5
1 2 3 4 5
1 2
1 3
2 4
2 5
1 2 3 4 5
1 2
1 3
2 4
2 5
样例输出
12
样例说明
选择3、4、5号点,权值和为 3+4+5 = 12 。
数据规模与约定
对于20%的数据, n <= 20。
对于50%的数据, n <= 1000。
对于100%的数据, n <= 100000。
权值均为不超过1000的正整数。
#include<stdio.h>
#include<vector>
#include<iostream>
using namespace std;
vector<int>node[100005];
int dp[100005][2],vist[100005],val[100005];
int max(int a,int b)
{
return a>b?a:b;
}
void dfs(int p)
{
dp[p][0]=0; dp[p][1]=val[p];
vist[p]=1;
int len=node[p].size();
for(int i=0;i<len;i++)
{
int son=node[p][i];
if(vist[son])continue;
dfs(son);
dp[p][1]+=dp[son][0];
dp[p][0]+=max(dp[son][0],dp[son][1]);
}
}
int main()
{
int n,a,b,MAX;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&val[i]);vist[i]=0;
}
for(int i=1;i<n;i++)
{
scanf("%d%d",&a,&b);
node[a].push_back(b);
node[b].push_back(a);
}
dfs(1);
MAX=dp[1][0];
MAX=max(MAX,dp[1][1]);
printf("%d\n",MAX);
}