1 条题解

  • 0
    @ 2025-11-11 20:18:08

    E86 换根DP CF1324F Maximum White Subtree

    // 换根DP O(n)
    #include <bits/stdc++.h>
    using namespace std;
    
    const int N=200005;
    vector<int> e[N];
    int n,a[N],f[N];
    
    void dfs(int u,int fa){
      f[u]=a[u];
      for(auto v:e[u]){
        if(v==fa)continue;
        dfs(v,u);
        if(f[v]>0) f[u]+=f[v];
      }
    }
    void dfs2(int u,int fa){
      for(auto v:e[u]){
        if(v==fa)continue;
        if(f[v]>0) f[v]=max(f[v],f[u]);
        else  f[v]=max(f[v],f[v]+f[u]);
        dfs2(v,u);
      }
    }
    int main(){
      ios::sync_with_stdio(false);
      cin.tie(0);cout.tie(0);
      cin>>n;
      for(int i=1;i<=n;++i){
        cin>>a[i];
        if(a[i]==0) a[i]=-1;
      }
      for(int i=1,x,y;i<n;++i){
        cin>>x>>y;
        e[x].push_back(y);
        e[y].push_back(x);
      }
      dfs(1,0);
      dfs2(1,0);
      for(int i=1;i<=n;++i)cout<<f[i]<<' ';
      return 0;
    }
    
    • 1

    信息

    ID
    1419
    时间
    2000ms
    内存
    256MiB
    难度
    3
    标签
    递交数
    39
    已通过
    22
    上传者