Advertisement
nikunjsoni

834

Apr 24th, 2021
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<unordered_set<int>> g;
  4.     vector<int> dp, count;
  5.     int n;
  6.    
  7.     vector<int> sumOfDistancesInTree(int N, vector<vector<int>>& edges) {
  8.         dp.assign(N, 0);
  9.         count.assign(N, 1);
  10.         g.resize(N);
  11.         n = N;
  12.        
  13.         // Create adj list.
  14.         for(int i=0; i<edges.size(); i++){
  15.             g[edges[i][0]].insert(edges[i][1]);
  16.             g[edges[i][1]].insert(edges[i][0]);
  17.         }
  18.    
  19.         // Create initial dp with dp[root] as overall answer.
  20.         dfs1(0, -1);
  21.        
  22.         // Manipulate dp for each node and find it's answer.
  23.         dfs2(0, -1);
  24.         return dp;
  25.     }
  26.    
  27.     void dfs1(int node, int parent){
  28.         for(int child: g[node]){
  29.             if(child == parent) continue;
  30.             dfs1(child, node);
  31.             count[node] += count[child];
  32.             dp[node] += (dp[child]+count[child]);
  33.         }
  34.     }
  35.    
  36.     void dfs2(int node, int parent){
  37.         for(int child: g[node]){
  38.             if(child == parent) continue;
  39.             // For each child, subtract the size of child's subtree as these many are downward edges from parent.
  40.             // Also add (N-count[child]), these are number of nodes that exist in upward tree.
  41.             dp[child] = dp[node]-count[child] + n-count[child];
  42.             dfs2(child, node);
  43.         }
  44.     }
  45.    
  46. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement