码迷,mamicode.com
首页 > 其他好文 > 详细

Luogu P1122 最大子树和

时间:2019-10-08 21:45:30      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:ide   dfs   最大   题意   add   opened   span   target   tps   

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

 

Luogu P1122 最大子树和

标签:ide   dfs   最大   题意   add   opened   span   target   tps   

原文地址:https://www.cnblogs.com/mogeko/p/11637759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!