Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Complexity is O(V+E).
- //adjacency list
- //adj[i] contains all neighbours of i
- vector<int> adj[N];
- //functions as defined in the pretension
- int f[N],g[N],diameter;
- //pV is parent of node V
- void dfs(int V, int pV){
- //this vector will store f for all children of V
- vector<int> fValues;
- //traverse over all children
- for(auto v: adj[V]){
- if(v == pV) continue;
- dfs(v, V);
- fValues.push_back(f[v]);
- }
- //sort to get top two values
- //you can also get top two values without sorting(think about it) in O(n)
- //current complexity is n log n
- sort(fValues.begin(),fValues.end());
- f[V] = 0;
- g[V] = 0;
- //update f for current node
- if(not fValues.empty()) f[V] = 1 + fValues.back();
- if(fValues.size()>=2)
- g[V] = 2 + fValues.back() + fValues[fValues.size()-2];
- diameter = max(diameter, max(f[V], g[V]));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement