ja / en
Overview

getFarthestVertex(最遠頂点を求める)

2024/07/30
1 min read

Purpose

Finds the farthest vertex from a specified vertex in a tree.

Time Complexity

O(n)O(n)

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;
}

Depended on

Verify👍

https://atcoder.jp/contests/typical90/submissions/57586680