最大子树和(树形dp)

  • 题意

题目链接:https://www.luogu.com.cn/problem/P1122

给一棵树,树上的每个节点都有一个值,然后你可以剪掉一些节点,问最后你能得到的最大的和。(因为有些节点的值为负数。)

  • 思路

典型树形dp。跑一遍dfs就行。
从 1 开始搜,f[i] 代表以 i 为根节点往下能得到的最大值,然后我们从 1 开始搜,如果 f[u] > 0,那么就说明这个子树不需要修剪,直接加上就行了。反之,不加。思路非常简单。

  • 代码

#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
#include<queue>
#include<math.h>
#include<stack>
#include<map>
#include<list>
#include<unordered_set>
#include<unordered_map>
#define endl '\n';
//#define int long long;
using namespace std;
typedef long long ll; 
const int N = 2e4+10;
int n, m, k;
int val[N], f[N];
vector<int> tree[N];

void dfs(int u, int fa){
    f[u] = val[u];
    for (auto t : tree[u]){
        if (t != fa){
            dfs(t, u);
            if (f[t] > 0)f[u] += f[t];
        }
    }
    return;
}

void sovle(){
    cin >> n; 
    for (int i = 1; i <= n; i ++)cin >> val[i];
    for (int i = 1; i <= n-1; i ++){
        int x, y;
        cin >> x >> y;
        tree[x].push_back(y);
        tree[y].push_back(x);
    }
    dfs(1, 0);
    int ans = -1000000;
    for (int i = 1; i <= n; i ++){
        ans = max(ans, f[i]);
    }

    cout << ans << endl;
}

int main()
{	
    int t = 1; 
    //scanf("%d", &t);
    
    while (t --){
        sovle();
    }

    return 0;
}



posted @ 2023-09-23 16:58  shunn  阅读(58)  评论(0)    收藏  举报