Purpose
Finds the farthest vertex from a specified vertex in a tree.
Time Complexity
Depends
Usage
Declaration
auto res = getFarthestVertex(g,s);Get the index of the farthest vertex using res.v. Get the distance to the farthest vertex using res.cost.
Implementation
struct getFarthestVertex_return { int v, cost;};getFarthestVertex_return getFarthestVertex(DirectedGraph &_g, int _v) { queue<pair<int, int>> q; vector<int> t(_g.n, -1); q.push({_v, 0}); getFarthestVertex_return res = {-1, -1}; while (!q.empty()) { auto p = q.front(); q.pop(); bool tr = true; for (auto &i : _g.g[p.first]) if (t[i.to] == -1) { tr = false; q.push({i.to, p.second + i.cost}); t[i.to] = p.second + i.cost; } if (tr) res = {p.first, p.second}; } return res;}