Luogu P1122 largest sub-tree and

Luogu P1122 largest sub-tree and

Maintenance DP array \ (F \) , where \ (f [x] \) represented by \ (X \) is the aesthetic appearance of the number of sub-root node.
Then for any node \ (U \) , there are \ (f [u] = \ sum f [v] (v \ in u subtree) \) .
Last updated each time you exit DFS when it \ (ans \) can be.

#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;
}

Guess you like

Origin www.cnblogs.com/luoshui-tianyi/p/11744188.html