Advertisement
111-111-111

Diameter of a tree

Apr 10th, 2020
403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. // Complexity is O(V+E).
  2.  
  3. //adjacency list
  4. //adj[i] contains all neighbours of i
  5. vector<int> adj[N];
  6.  
  7. //functions as defined in the pretension
  8. int f[N],g[N],diameter;
  9.  
  10. //pV is parent of node V
  11. void dfs(int V, int pV){
  12.     //this vector will store f for all children of V
  13.     vector<int> fValues;
  14.  
  15.     //traverse over all children
  16.     for(auto v: adj[V]){
  17.     if(v == pV) continue;
  18.     dfs(v, V);
  19.     fValues.push_back(f[v]);
  20.     }
  21.  
  22.     //sort to get top two values
  23.     //you can also get top two values without sorting(think about it) in O(n)
  24.     //current complexity is n log n
  25.     sort(fValues.begin(),fValues.end());
  26.  
  27.     f[V] = 0;
  28.     g[V] = 0;
  29.     //update f for current node
  30.     if(not fValues.empty()) f[V] = 1 + fValues.back();
  31.  
  32.     if(fValues.size()>=2)
  33.          g[V] = 2 + fValues.back() + fValues[fValues.size()-2];
  34.  
  35.     diameter = max(diameter, max(f[V], g[V]));
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement