首页 > 其他 > 详细

洛谷 1122 最大子树和

时间:2018-08-26 20:25:17      阅读:142      评论:0      收藏:0      [点我收藏+]

技术分享图片

【题解】

  直接做树形DP即可。f[i]表示取i及其子树的最大的美丽指数,若某个儿子son满足f[son]>0,f[i]就加上f[son].

技术分享图片
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #define LL long long
 5 #define N 200010
 6 #define rg register
 7 using namespace std;
 8 int n,m,ans=-2e9,tot,last[N],f[N];
 9 struct edge{
10     int to,pre;
11 }e[N];
12 inline int read(){
13     int k=0,f=1; char c=getchar();
14     while(c<0||c>9)c==-&&(f=-1),c=getchar();
15     while(0<=c&&c<=9)k=k*10+c-0,c=getchar();
16     return k*f;
17 } 
18 void dfs(int x,int fa){
19     for(rg int i=last[x],to;i;i=e[i].pre)if((to=e[i].to)!=fa){
20         dfs(to,x); if(f[to]>0) f[x]+=f[to];
21     }
22     ans=max(ans,f[x]);
23 }
24 int main(){
25     n=read();
26     for(rg int i=1;i<=n;i++) f[i]=read();
27     for(rg int i=1;i<n;i++){
28         int u=read(),v=read();
29         e[++tot]=(edge){v,last[u]}; last[u]=tot;
30         e[++tot]=(edge){u,last[v]}; last[v]=tot;
31     }
32     dfs(1,0);
33     printf("%d\n",ans);
34 }
View Code

 

洛谷 1122 最大子树和

原文:https://www.cnblogs.com/DriverLao/p/9538494.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!