Loading

洛谷-P1122 最大子树和

最大子树和

树形dp

对于一个节点来说,如果删除掉一个连接子节点的边,则以该子节点为根的子树上面的贡献都会变成 \(0\)

设计状态:\(dp[u]\),表示以 \(u\) 为根的子树中,贡献值最大为多少

状态转移:\(dp[u] = max(0, dp[v])\)\(v\)\(u\) 的子节点,\(0\) 的话表示删除该边,\(dp[v]\) 的话表示保留该边

注意:最后一定要至少要存在一个节点

答案不一定以 \(1\) 为根,所有子树都有可能是答案

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <array>
using namespace std;
typedef long long ll;
vector<ll>dp;
vector<vector<int>>gra;

void dps(int now, int pre)
{
    for(int nex : gra[now])
    {
        if(nex == pre) continue;
        dps(nex, now);
        dp[now] += max(0ll, dp[nex]);
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n;
    cin >> n;
    dp.resize(n + 1);
    gra.resize(n + 1);
    for(int i=1; i<=n; i++) cin >> dp[i];
    for(int i=1; i<n; i++)
    {
        int a, b;
        cin >> a >> b;
        gra[a].push_back(b);
        gra[b].push_back(a);
    }
    dps(1, 1);
    ll ans = dp[1];
    for(int i=1; i<=n; i++) ans = max(ans, dp[i]);
    cout << ans << endl;
    return 0;
}
posted @ 2022-11-01 20:19  dgsvygd  阅读(32)  评论(0)    收藏  举报