Open GaurangTandon opened 4 years ago
int diameter(int node, VI &visited, VVI &adj, VI &distances) { VI seen = {}; queue<int> q; q.push(node); distances[node] = 0; visited[node] = true; int farthest = node; while(!q.empty()) { auto node = q.front(); q.pop(); seen.push_back(node); for (auto neigh : adj[node]) { if (not visited[neigh]) { visited[neigh] = true; distances[neigh] = 1 + distances[node]; if (distances[farthest] < distances[neigh]) farthest = neigh; q.push(neigh); } } } for (auto x : seen) distances[x] = INT_MIN, visited[x] = false; q.push(farthest); distances[farthest] = 0; visited[farthest] = true; while(!q.empty()) { auto node = q.front(); q.pop(); seen.push_back(node); for (auto neigh : adj[node]) { if (not visited[neigh]) { visited[neigh] = true; distances[neigh] = 1 + distances[node]; if (distances[farthest] < distances[neigh]) farthest = neigh; q.push(neigh); } } } return distances[farthest]; }
Call it like this:
VI visited(n + 1, false); VI distances(n + 1, 0); for (int i = 1; i <= n; i++) { if (!visited[i]) { diameter(i, visited, adj, distances); } }
Tested on problem 455C
Find a place to put this in our repo. Not everything needs to be in the icpc notebook, some things can be there just for easy copy-paste :P
Call it like this:
Tested on problem 455C
Find a place to put this in our repo. Not everything needs to be in the icpc notebook, some things can be there just for easy copy-paste :P