Advertisement
RaFiN_

dp on tree

Jul 1st, 2019
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. /* dp on tree */
  2.  
  3.  
  4. ll n,arr[MAX];vi v[MAX];ll choto[MAX],boro[MAX],ans;
  5.  
  6. void dfs1(int s,int p = 0)
  7. {
  8.     choto[s] = arr[s];
  9.     for(auto it : v[s])
  10.     {
  11.         if(it==p)continue;
  12.         dfs1(it,s);
  13.         boro[s]+=choto[it]+boro[it];
  14.         choto[s]+=choto[it];
  15.     }
  16. }
  17.  
  18.  
  19. void dfs2(int s,int p = 0)
  20. {
  21.     if(p)
  22.         boro[s]=boro[p]+choto[p]-choto[s]-choto[s];
  23.     if(p)
  24.         choto[s]=choto[p];
  25.     ans = max(ans,boro[s]);
  26.     for(auto it : v[s])
  27.     {
  28.         if(it==p)continue;
  29.         dfs2(it,s);
  30.     }
  31. }
  32.  
  33.  
  34. int main()
  35. {
  36.     booster()
  37.  
  38.     cin>>n;
  39.  
  40.     for(int i = 1;i<=n;i++)cin>>arr[i];
  41.  
  42.     for(int i = 0;i<n-1;i++)
  43.     {
  44.         int a,b;
  45.         cin>>a>>b;
  46.         v[a].pb(b);
  47.         v[b].pb(a);
  48.     }
  49.  
  50.     dfs1(1);
  51.  
  52.     dfs2(1);
  53.  
  54.     cout<<ans;
  55.  
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement