loj10160. 「一本通 5.2 练习 3」周年纪念晚会

本文介绍了一个简单的树形动态规划(DP)问题,并提供了一段C++实现代码。该代码使用了自顶向下的递归方式来解决问题,通过记录每个节点的最大价值来更新父节点的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:
  挺简单的树形dp

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;
const int maxn = 200010;
void qread(int &x) {
    x = 0;
    register int ch = getchar(), flag = 0;
    while(ch < '0' || ch > '9')    {if(ch == '-')    flag = 1;    ch = getchar();}
    while(ch >= '0' && ch <= '9')    x = 10 * x + ch - 48, ch = getchar();
    if(flag)    x = -x;
}
int n, rt = 0, cnt;

int val[maxn];
int deep[maxn];
int f[maxn];

int head[maxn];
int go[maxn << 1];
int nxt[maxn << 1];

int dp[maxn][2];

inline void init(){
    qread(n);
    for(int i=1; i<=n; ++i)
        qread(val[i]);
    int x, y;
    qread(x), qread(y);
    while(x || y){
        go[++cnt] = x;
        nxt[cnt] = head[y];
        head[y] = cnt;
        f[x] = y;
        qread(x), qread(y);
    }
    for(int i=1; i<=n; ++i)
        if(!f[i])
            rt = i;    
}

void DP(int x){
    dp[x][1] = val[x];
    for(int i = head[x]; i; i = nxt[i]){
        DP(go[i]);
        dp[x][1] += dp[go[i]][0];
        dp[x][0] += max(dp[go[i]][0], dp[go[i]][1]);
    }
}
int main(void){
    init();
    DP(rt);
    printf("%d\n", max(dp[rt][0], dp[rt][1]));
}

 

---恢复内容结束---

转载于:https://www.cnblogs.com/junk-yao-blog/p/9492995.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值