/* 返回顶部 */

Luogu P1122 最大子树和

gate

树形dp水题,题意见题目w

直接判断是否选儿子即可。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#define MogeKo qwq
using namespace std;

const int maxn = 40005;
int n,x,y,cnt,ans,a[maxn],f[maxn];
int head[maxn],to[maxn],nxt[maxn];

void add(int x,int y) {
    to[++cnt] = y;
    nxt[cnt] = head[x];
    head[x] = cnt;
}

void dfs(int x,int fa) {
    f[x] = a[x];
    for(int i = head[x]; i; i = nxt[i]) {
        int v = to[i];
        if(v == fa) continue;
        dfs(v,x);
        f[x] = max(f[x],f[x]+f[v]);
    }
    ans = max(ans,f[x]);
}

int main() {
    scanf("%d",&n);
    for(int i = 1; i <= n; i++)
        scanf("%d",&a[i]);
    for(int i = 1; i <= n-1; i++) {
        scanf("%d%d",&x,&y);
        add(x,y),add(y,x);
    }
    dfs(1,1);
    printf("%d",ans);
    return 0;
}
View Code

 

posted @ 2019-10-08 20:32  Mogeko  阅读(90)  评论(0编辑  收藏  举报