zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    一些想说的事
    化学离子平衡作业偷懒神器
    solution
    SGU 刷题记
    INT128
    # 字典树的指针写法 1.
    CSP-S2 游记
    Tarjan 【整理】
    HGOI 20191106
    20191101
  • 原文地址:https://www.cnblogs.com/mogeko/p/11637759.html
Copyright © 2011-2022 走看看