Advertisement
111-111-111

Maximum subset of nodes such that no two adjacent node in Tr

Apr 10th, 2020
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. // Complexity is O(V+E).
  2.  
  3. //adjacency list
  4. //adj[i] contains all neighbors of i
  5. vector<int> adj[N];
  6.  
  7. // coins attached with v
  8. int C[N];
  9.  
  10. // dp1,dp2 denoting maximum coins possible by choosing nodes from subtree
  11. //of node V and if we include node V in our answer or not, respectively.
  12. int dp1[N],dp2[N];
  13.  
  14. //pV is parent of node V
  15. void dfs(int V, int pV){
  16.  
  17.     //for storing sums of dp1 and max(dp1, dp2) for all children of V
  18.     int sum1=0, sum2=0;
  19.  
  20.     //traverse over all children
  21.     for(auto v: adj[V]){
  22.     if(v == pV) continue;
  23.     dfs(v, V);
  24.     sum1 += dp2[v];
  25.     sum2 += max(dp1[v], dp2[v]);
  26.     }
  27.  
  28.     dp1[V] = C[V] + sum1;
  29.     dp2[V] = sum2;
  30. }
  31.  
  32. int main(){
  33.     int n;
  34.     cin >> n;
  35.  
  36.     for(int i=0; i<n; i++){
  37.         cin >> C[i];
  38.     }
  39.  
  40.     for(int i=1; i<n; i++){
  41.     cin >> u >> v;
  42.     adj[u].push_back(v);
  43.     adj[v].push_back(u);
  44.     }
  45.  
  46.     dfs(0, -1);
  47.     int ans = max(dp1[0], dp2[0]);
  48.     cout << ans << endl;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement