Luogu P1122 最大子树和

Luogu P1122 最大子树和

维护DP数组\(f\),其中\(f[x]\)表示以\(x\)为根节点的子数的美观程度。
则对于任意节点\(u\),有\(f[u]=\sum f[v](v\in u的子树)\)
最后每次退出DFS的时候更新一下\(ans\)即可。

#include<bits/stdc++.h>
#define N 16010

using namespace std;

int n,cnt,ans;
int a[N],head[N],f[N];

struct node {
    int nxt,to;
}edge[N*2];

void addEdge(int u,int v) {
    edge[++cnt]=(node){head[u],v};
    head[u]=cnt;
    return;
}

void Read() {
    scanf("%d",&n);
    for(int i=1;i<=n;i++) {
        scanf("%d",&a[i]);
    }
    for(int i=1;i<=n-1;i++) {
        int a,b;
        scanf("%d%d",&a,&b);
        addEdge(a,b);
        addEdge(b,a);
    }
    return;
}

void DFS(int x,int fa) {
    f[x]=a[x];
    for(int i=head[x];i;i=edge[i].nxt) {
        int v=edge[i].to;
        if(v!=fa) {
            DFS(v,x);
            f[x]+=max(0,f[v]);
        }
    }
    ans=max(ans,f[x]);
    return;
}

void Print() {
    printf("%d",ans);
}

int main()
{
    Read();
    DFS(1,0);
    Print();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/luoshui-tianyi/p/11744188.html