码迷,mamicode.com
首页 > 其他好文 > 详细

题解:最大子树和

时间:2019-12-07 23:33:02      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:pac   ext   nod   node   mes   www   rom   ons   class   

题目链接

solution

板子题,从最大的下手找

#include<bits/stdc++.h>
using namespace std;
const int N = 16500;
int s[N],n;
struct node{
    int next,to;
}edge[N<<1];
int head[N],cnt;
inline void add(int from,int to) {
    edge[++cnt].to=to;edge[cnt].next=head[from];
    head[from]=cnt;
}
void dfs(int u,int f) {
    for(int i=head[u];i;i=edge[i].next) {
        int v=edge[i].to;
        if(v==f) continue;
        dfs(v,u);
        s[u]+=max(s[v],0);
    }
}
int main() {
    cin>>n;
    int root=0;s[root]=-1;
    for(int i=1;i<=n;i++) {cin>>s[i];if(s[i]>s[root]) root=i;}
    for(int i=1;i<n;i++) {
        int a,b;cin>>a>>b;
        add(a,b),add(b,a);
    }
    dfs(root,root);
    cout<<s[root];
    return 0;
}

题解:最大子树和

标签:pac   ext   nod   node   mes   www   rom   ons   class   

原文地址:https://www.cnblogs.com/skkyk/p/12003632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!