Description
给出一个有n个节点的子树以及每个点的权值,求一棵权值和最大的子树
Input
第一行为一整数n表示树上节点数,第二行n个整数表示每个节点的权值,之后n-1行每行两个整数表示树上的一条边(1<=n<=16000)
Output
输出子树的最大权值和
Sample Input
5
-1 1 3 1 -1
4 1
1 3
1 2
4 5
Sample Output
4
Solution
以dp[i]表示第i为根的子树的最大权值和,则有
dp[u]=v[u]+sum(max(0,dp[v])),其中fa[v]=u
则max(dp[i])即为答案
Code
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define maxn 22222
struct Edge
{
int to,next;
}edge[2*maxn];
int n,dp[maxn],head[maxn],tot;
void init()
{
tot=0;
memset(head,-1,sizeof(head));
}
void add(int u,int v)
{
edge[tot].to=v;
edge[tot].next=head[u];
head[u]=tot++;
}
void dfs(int u,int fa)
{
for(int i=head[u];~i;i=edge[i].next)
{
int v=edge[i].to;
if(v==fa)continue;
dfs(v,u);
dp[u]+=max(0,dp[v]);
}
}
int main()
{
scanf("%d",&n);
init();
for(int i=1;i<=n;i++)scanf("%d",&dp[i]);
for(int i=1;i<n;i++)
{
int u,v;
scanf("%d%d",&u,&v);
add(u,v),add(v,u);
}
dfs(1,0);
int ans=-1000;
for(int i=1;i<=n;i++)ans=max(ans,dp[i]);
printf("%d\n",ans);
return 0;
}