SGU 143 Long Live the Queen(树形DP)

49 篇文章 0 订阅

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值