[蓝桥杯][2015年第六届真题]生命之树

最大子段和的树上扩展。

状态表示:
(f[u]):在以(u)为根的子树中包含u的所有连通块中的权值的最大值。
状态转移:
如果子树中存在权值和为正的连通块,则包含上该子树,否则丢弃。

[f[u]=w[u]+max(f[s_1],0)+max(f[s_2],0)+cdots+max(f[s_k],0) ]

(s_1,s_2,cdots,s_k)(u)的孩子。

const int N=1e5+10;
vector<int> g[N];
LL f[N];
int w[N];
int n;

void dfs(int u,int fa)
{
    f[u]=w[u];

    for(int i=0;i<g[u].size();i++)
    {
        int j=g[u][i];
        if(j == fa) continue;
        dfs(j,u);
        f[u]+=max(0LL,f[j]);
    }
}

int main()
{
    cin>>n;

    for(int i=1;i<=n;i++) cin>>w[i];

    for(int i=0;i<n-1;i++)
    {
        int a,b;
        cin>>a>>b;
        g[a].pb(b);
        g[b].pb(a);
    }

    dfs(1,-1);

    LL res=0;
    for(int i=1;i<=n;i++)
        res=max(res,f[i]);
    cout<<res<<endl;
    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/fxh0707/p/14643003.html