Tree Diameter
(graph/tree/diameter.hpp)
- View this file on GitHub
- Last update: 2026-08-13 01:41:40+09:00
- Include:
#include "graph/tree/diameter.hpp"
Overview
tree_diameter(g) returns a longest path in an undirected tree. It also works
on a forest and returns the longest diameter among its connected components.
The input uses m1une::graph::Graph<T> and should be built with add_edge.
Inactive edges are ignored.
For weighted trees, edge costs should be non-negative.
Result
TreeDiameter<T> contains:
| Member | Description |
|---|---|
cost |
Sum of edge costs on the diameter path. |
edge_count |
Number of edges on the restored path. |
from, to
|
Endpoints of the path, or -1 for an empty graph. |
vertices |
Vertices on the path from from to to. |
edge_ids |
Edge ids on the path from from to to. |
empty() |
Returns whether no path vertices exist. |
Function
| Function | Description | Complexity |
|---|---|---|
tree_diameter(g) |
Finds a diameter path. | $O(N)$ |
Example
#include "graph/graph.hpp"
#include "graph/tree/diameter.hpp"
#include <iostream>
int main() {
m1une::graph::Graph<int> g(4);
g.add_edge(0, 1, 2);
g.add_edge(1, 2, 3);
g.add_edge(1, 3, 4);
auto diameter = m1une::tree::tree_diameter(g);
std::cout << diameter.cost << "\n"; // 7
}
Depends on
Required by
Verified with
verify/graph/cow_game.test.cpp
verify/graph/graph_algorithms.test.cpp
verify/graph/range_edge_graph.test.cpp
verify/graph/tree/tree_algorithms.test.cpp
verify/graph/tree/tree_diameter.test.cpp
Code
#ifndef M1UNE_TREE_DIAMETER_HPP
#define M1UNE_TREE_DIAMETER_HPP 1
#include <algorithm>
#include <vector>
#include "../graph.hpp"
namespace m1une {
namespace tree {
template <class T = int>
struct TreeDiameter {
T cost;
int edge_count;
int from;
int to;
std::vector<int> vertices;
std::vector<int> edge_ids;
bool empty() const {
return vertices.empty();
}
};
namespace internal {
template <class T>
struct FarthestResult {
int vertex;
std::vector<char> seen;
std::vector<T> dist;
std::vector<int> parent;
std::vector<int> parent_edge;
};
template <class T>
FarthestResult<T> farthest_from(const m1une::graph::Graph<T>& g, int start) {
int n = g.size();
FarthestResult<T> result;
result.vertex = start;
result.seen.assign(n, false);
result.dist.assign(n, T(0));
result.parent.assign(n, -1);
result.parent_edge.assign(n, -1);
std::vector<int> stack = {start};
result.seen[start] = true;
while (!stack.empty()) {
int v = stack.back();
stack.pop_back();
if (result.dist[result.vertex] < result.dist[v]) result.vertex = v;
for (const auto& e : g[v]) {
if (!e.alive) continue;
if (result.seen[e.to]) continue;
result.seen[e.to] = true;
result.dist[e.to] = result.dist[v] + e.cost;
result.parent[e.to] = v;
result.parent_edge[e.to] = e.id;
stack.push_back(e.to);
}
}
return result;
}
} // namespace internal
template <class T>
TreeDiameter<T> tree_diameter(const m1une::graph::Graph<T>& g) {
int n = g.size();
TreeDiameter<T> best;
best.cost = T(0);
best.edge_count = 0;
best.from = -1;
best.to = -1;
if (n == 0) return best;
std::vector<char> done(n, false);
for (int start = 0; start < n; start++) {
if (done[start]) continue;
auto first = internal::farthest_from(g, start);
for (int v = 0; v < n; v++) {
if (first.seen[v]) done[v] = true;
}
auto second = internal::farthest_from(g, first.vertex);
int a = first.vertex;
int b = second.vertex;
T cost = second.dist[b];
if (best.from != -1 && !(best.cost < cost)) continue;
best.cost = cost;
best.from = a;
best.to = b;
best.vertices.clear();
best.edge_ids.clear();
for (int v = b; v != -1; v = second.parent[v]) {
best.vertices.push_back(v);
if (v != a) best.edge_ids.push_back(second.parent_edge[v]);
}
std::reverse(best.vertices.begin(), best.vertices.end());
std::reverse(best.edge_ids.begin(), best.edge_ids.end());
best.edge_count = int(best.edge_ids.size());
}
return best;
}
} // namespace tree
} // namespace m1une
#endif // M1UNE_TREE_DIAMETER_HPP#line 1 "graph/tree/diameter.hpp"
#include <algorithm>
#include <vector>
#line 1 "graph/graph.hpp"
#include <array>
#include <cassert>
#include <utility>
#line 8 "graph/graph.hpp"
namespace m1une {
namespace graph {
template <class T = int>
struct Edge {
using cost_type = T;
int from;
int to;
T cost;
int id;
bool alive;
Edge() : from(-1), to(-1), cost(T()), id(-1), alive(true) {}
Edge(int from_, int to_, T cost_ = T(1), int id_ = -1, bool alive_ = true)
: from(from_), to(to_), cost(cost_), id(id_), alive(alive_) {}
int other(int v) const {
assert(v == from || v == to);
return from ^ to ^ v;
}
};
template <class T = int>
struct Graph {
using edge_type = Edge<T>;
using cost_type = T;
private:
struct EdgePositions {
std::array<std::pair<int, int>, 2> value{};
int size = 0;
void push_back(std::pair<int, int> position) {
assert(size < 2);
value[size++] = position;
}
};
int _n;
int _edge_count;
std::vector<std::vector<edge_type>> _g;
std::vector<EdgePositions> _edge_positions;
public:
Graph() : _n(0), _edge_count(0) {}
explicit Graph(int n) : _n(n), _edge_count(0), _g(n) {
assert(0 <= n);
}
int size() const {
return _n;
}
bool empty() const {
return _n == 0;
}
int edge_count() const {
return _edge_count;
}
int add_vertex() {
_g.emplace_back();
return _n++;
}
int add_directed_edge(int from, int to, T cost = T(1)) {
assert(0 <= from && from < _n);
assert(0 <= to && to < _n);
int id = _edge_count++;
int idx = int(_g[from].size());
_g[from].push_back(edge_type(from, to, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({from, idx});
return id;
}
int add_edge(int u, int v, T cost = T(1)) {
assert(0 <= u && u < _n);
assert(0 <= v && v < _n);
int id = _edge_count++;
int u_idx = int(_g[u].size());
_g[u].push_back(edge_type(u, v, cost, id));
int v_idx = int(_g[v].size());
_g[v].push_back(edge_type(v, u, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({u, u_idx});
_edge_positions.back().push_back({v, v_idx});
return id;
}
void set_edge_alive(int id, bool alive) {
assert(0 <= id && id < _edge_count);
for (int i = 0; i < _edge_positions[id].size; ++i) {
auto [v, idx] = _edge_positions[id].value[i];
_g[v][idx].alive = alive;
}
}
void erase_edge(int id) {
set_edge_alive(id, false);
}
void revive_edge(int id) {
set_edge_alive(id, true);
}
bool is_edge_alive(int id) const {
assert(0 <= id && id < _edge_count);
assert(_edge_positions[id].size != 0);
auto [v, idx] = _edge_positions[id].value[0];
return _g[v][idx].alive;
}
const std::vector<edge_type>& operator[](int v) const {
assert(0 <= v && v < _n);
return _g[v];
}
std::vector<edge_type>& operator[](int v) {
assert(0 <= v && v < _n);
return _g[v];
}
const std::vector<std::vector<edge_type>>& adjacency() const {
return _g;
}
std::vector<std::vector<edge_type>>& adjacency() {
return _g;
}
std::vector<edge_type> edges(bool include_inactive = false) const {
std::vector<edge_type> result;
result.reserve(_edge_count);
std::vector<char> used(_edge_count, false);
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
if (!include_inactive && !e.alive) continue;
if (0 <= e.id && e.id < _edge_count) {
if (used[e.id]) continue;
used[e.id] = true;
}
result.push_back(e);
}
}
return result;
}
Graph reversed() const {
Graph result(_n);
result._edge_count = _edge_count;
result._edge_positions.assign(_edge_count, {});
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
int idx = int(result._g[e.to].size());
result._g[e.to].push_back(edge_type(e.to, e.from, e.cost, e.id, e.alive));
if (0 <= e.id && e.id < _edge_count) result._edge_positions[e.id].push_back({e.to, idx});
}
}
return result;
}
};
} // namespace graph
} // namespace m1une
#line 8 "graph/tree/diameter.hpp"
namespace m1une {
namespace tree {
template <class T = int>
struct TreeDiameter {
T cost;
int edge_count;
int from;
int to;
std::vector<int> vertices;
std::vector<int> edge_ids;
bool empty() const {
return vertices.empty();
}
};
namespace internal {
template <class T>
struct FarthestResult {
int vertex;
std::vector<char> seen;
std::vector<T> dist;
std::vector<int> parent;
std::vector<int> parent_edge;
};
template <class T>
FarthestResult<T> farthest_from(const m1une::graph::Graph<T>& g, int start) {
int n = g.size();
FarthestResult<T> result;
result.vertex = start;
result.seen.assign(n, false);
result.dist.assign(n, T(0));
result.parent.assign(n, -1);
result.parent_edge.assign(n, -1);
std::vector<int> stack = {start};
result.seen[start] = true;
while (!stack.empty()) {
int v = stack.back();
stack.pop_back();
if (result.dist[result.vertex] < result.dist[v]) result.vertex = v;
for (const auto& e : g[v]) {
if (!e.alive) continue;
if (result.seen[e.to]) continue;
result.seen[e.to] = true;
result.dist[e.to] = result.dist[v] + e.cost;
result.parent[e.to] = v;
result.parent_edge[e.to] = e.id;
stack.push_back(e.to);
}
}
return result;
}
} // namespace internal
template <class T>
TreeDiameter<T> tree_diameter(const m1une::graph::Graph<T>& g) {
int n = g.size();
TreeDiameter<T> best;
best.cost = T(0);
best.edge_count = 0;
best.from = -1;
best.to = -1;
if (n == 0) return best;
std::vector<char> done(n, false);
for (int start = 0; start < n; start++) {
if (done[start]) continue;
auto first = internal::farthest_from(g, start);
for (int v = 0; v < n; v++) {
if (first.seen[v]) done[v] = true;
}
auto second = internal::farthest_from(g, first.vertex);
int a = first.vertex;
int b = second.vertex;
T cost = second.dist[b];
if (best.from != -1 && !(best.cost < cost)) continue;
best.cost = cost;
best.from = a;
best.to = b;
best.vertices.clear();
best.edge_ids.clear();
for (int v = b; v != -1; v = second.parent[v]) {
best.vertices.push_back(v);
if (v != a) best.edge_ids.push_back(second.parent_edge[v]);
}
std::reverse(best.vertices.begin(), best.vertices.end());
std::reverse(best.edge_ids.begin(), best.edge_ids.end());
best.edge_count = int(best.edge_ids.size());
}
return best;
}
} // namespace tree
} // namespace m1une