Rerooting DP
(graph/tree/rerooting_dp.hpp)
- View this file on GitHub
- Last update: 2026-08-13 01:41:40+09:00
- Include:
#include "graph/tree/rerooting_dp.hpp"
Overview
rerooting_dp is a generic all-roots tree DP helper. It computes one DP value
for every possible root of an undirected tree, or for every vertex in each
component of a forest.
The input uses m1une::graph::Graph<T> and should be built with add_edge.
Inactive edges are ignored.
Function
template <class T, class DP, class Merge, class AddVertex, class AddEdge>
std::vector<DP> rerooting_dp(
const m1une::graph::Graph<T>& g,
DP id,
Merge merge,
AddVertex add_vertex,
AddEdge add_edge
);
The callbacks mean:
| Callback | Meaning |
|---|---|
id |
Identity DP value for merge. |
merge(a, b) |
Combines independent neighbor contributions. It should be associative. |
add_vertex(acc, v) |
Finalizes the merged contributions at vertex v. |
add_edge(dp, e) |
Converts a neighbor-side DP value through adjacency edge e. |
For an edge contribution used at vertex v, e is the adjacency edge from v
to that neighbor.
DP Meaning
Think of the tree as being cut at an edge. A DP value represents one connected
side of the cut, rooted at the vertex closest to the edge.
For a vertex v, each neighbor to gives one independent contribution:
contribution_from_to = add_edge(dp_of_side_rooted_at_to, edge_v_to);
Then all neighbor contributions are merged, and v itself is added:
answer[v] = add_vertex(merge(all neighbor contributions), v);
The library computes this for every v. When it sends information from v to
one child, it merges all contributions except that child, applies
add_vertex(..., v), and passes that value across the edge later. This is the
usual rerooting trick; prefix and suffix products make the “all except one”
merge fast.
Most tree DPs use a commutative merge, such as +, max, or min. The
implementation applies merge in adjacency-list order, so non-commutative
operations are deterministic but depend on that order.
How to Design the Callbacks
Use this checklist:
- Decide what
DPmeans for a rooted connected piece. - Choose
id, the value for an empty set of neighbor contributions. - Define
merge(a, b), which combines two independent neighbor sides. - Define
add_edge(dp, e), which changes distances or values when the piece is viewed from the other endpoint of edgee. - Define
add_vertex(acc, v), which adds the current vertex after all neighbor sides have been merged.
If the final answer for root v is “the DP of the whole tree rooted at v”,
then it is exactly result[v].
Complexity
rerooting_dp runs in $O(N)$ callback calls on a tree.
Example: Farthest Distance
The following computes the eccentricity of each vertex: the maximum number of edges from that vertex to any other vertex.
Here DP is one integer:
- Meaning: maximum distance from the current root of this piece to a vertex in the piece.
-
id = 0: an empty set of children contributes distance0. -
merge = max: keep the farthest side. -
add_edge(dp, e) = dp + 1: crossing one unweighted edge increases every distance by1. -
add_vertex(acc, v) = acc: the current vertex has distance0, so it does not change the maximum.
#include "graph/graph.hpp"
#include "graph/tree/rerooting_dp.hpp"
#include <algorithm>
#include <iostream>
int main() {
m1une::graph::Graph<int> g(4);
g.add_edge(0, 1);
g.add_edge(1, 2);
g.add_edge(1, 3);
auto ecc = m1une::tree::rerooting_dp(
g,
0,
[](int a, int b) { return std::max(a, b); },
[](int acc, int) { return acc; },
[](int dp, const auto&) { return dp + 1; }
);
std::cout << ecc[0] << "\n"; // 2
}
Example: Sum of Distances
The following computes, for every vertex v, the sum of distances from v to
all vertices.
Use a DP state with:
-
size: number of vertices in this piece. -
sum: sum of distances from the current root of this piece to all vertices in the piece.
When crossing an edge of cost w, every distance increases by w, so
sum += size * w.
#include "graph/graph.hpp"
#include "graph/tree/rerooting_dp.hpp"
#include <iostream>
struct DP {
long long size;
long long sum;
};
int main() {
m1une::graph::Graph<long long> g(4);
g.add_edge(0, 1, 1);
g.add_edge(1, 2, 1);
g.add_edge(1, 3, 1);
auto res = m1une::tree::rerooting_dp(
g,
DP{0, 0},
[](DP a, DP b) {
return DP{a.size + b.size, a.sum + b.sum};
},
[](DP acc, int) {
return DP{acc.size + 1, acc.sum};
},
[](DP dp, const auto& e) {
return DP{dp.size, dp.sum + dp.size * e.cost};
}
);
std::cout << res[0].sum << "\n"; // dist(0,0)+dist(0,1)+dist(0,2)+dist(0,3) = 5
}
Common Patterns
For counting vertices:
id = 0
merge(a, b) = a + b
add_vertex(acc, v) = acc + 1
add_edge(dp, e) = dp
For maximum weighted distance:
id = 0
merge(a, b) = std::max(a, b)
add_vertex(acc, v) = acc
add_edge(dp, e) = dp + e.cost
For DP states with several fields, merge usually adds or takes the best of
each field, add_edge shifts the state across one edge, and add_vertex
accounts for the current vertex.
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
Code
#ifndef M1UNE_TREE_REROOTING_DP_HPP
#define M1UNE_TREE_REROOTING_DP_HPP 1
#include <vector>
#include "../graph.hpp"
namespace m1une {
namespace tree {
template <class T, class DP, class Merge, class AddVertex, class AddEdge>
std::vector<DP> rerooting_dp(const m1une::graph::Graph<T>& g, DP id, Merge merge, AddVertex add_vertex,
AddEdge add_edge) {
int n = g.size();
std::vector<int> parent(n, -2), parent_edge(n, -1), order;
order.reserve(n);
for (int root = 0; root < n; root++) {
if (parent[root] != -2) continue;
parent[root] = -1;
std::vector<int> stack = {root};
while (!stack.empty()) {
int v = stack.back();
stack.pop_back();
order.push_back(v);
for (const auto& e : g[v]) {
if (!e.alive) continue;
if (parent[e.to] != -2) continue;
parent[e.to] = v;
parent_edge[e.to] = e.id;
stack.push_back(e.to);
}
}
}
std::vector<DP> down(n, id), outside(n, id), answer(n, id);
for (int i = n - 1; i >= 0; i--) {
int v = order[i];
DP acc = id;
for (const auto& e : g[v]) {
if (!e.alive) continue;
if (parent[e.to] != v) continue;
acc = merge(acc, add_edge(down[e.to], e));
}
down[v] = add_vertex(acc, v);
}
for (int v : order) {
int d = int(g[v].size());
std::vector<DP> contrib(d, id);
for (int i = 0; i < d; i++) {
const auto& e = g[v][i];
if (!e.alive) continue;
if (parent[e.to] == v) {
contrib[i] = add_edge(down[e.to], e);
} else if (parent[v] == e.to && parent_edge[v] == e.id) {
contrib[i] = add_edge(outside[v], e);
}
}
std::vector<DP> pref(d + 1, id), suff(d + 1, id);
for (int i = 0; i < d; i++) pref[i + 1] = merge(pref[i], contrib[i]);
for (int i = d - 1; i >= 0; i--) suff[i] = merge(contrib[i], suff[i + 1]);
answer[v] = add_vertex(pref[d], v);
for (int i = 0; i < d; i++) {
const auto& e = g[v][i];
if (!e.alive) continue;
if (parent[e.to] != v) continue;
outside[e.to] = add_vertex(merge(pref[i], suff[i + 1]), v);
}
}
return answer;
}
} // namespace tree
} // namespace m1une
#endif // M1UNE_TREE_REROOTING_DP_HPP#line 1 "graph/tree/rerooting_dp.hpp"
#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 7 "graph/tree/rerooting_dp.hpp"
namespace m1une {
namespace tree {
template <class T, class DP, class Merge, class AddVertex, class AddEdge>
std::vector<DP> rerooting_dp(const m1une::graph::Graph<T>& g, DP id, Merge merge, AddVertex add_vertex,
AddEdge add_edge) {
int n = g.size();
std::vector<int> parent(n, -2), parent_edge(n, -1), order;
order.reserve(n);
for (int root = 0; root < n; root++) {
if (parent[root] != -2) continue;
parent[root] = -1;
std::vector<int> stack = {root};
while (!stack.empty()) {
int v = stack.back();
stack.pop_back();
order.push_back(v);
for (const auto& e : g[v]) {
if (!e.alive) continue;
if (parent[e.to] != -2) continue;
parent[e.to] = v;
parent_edge[e.to] = e.id;
stack.push_back(e.to);
}
}
}
std::vector<DP> down(n, id), outside(n, id), answer(n, id);
for (int i = n - 1; i >= 0; i--) {
int v = order[i];
DP acc = id;
for (const auto& e : g[v]) {
if (!e.alive) continue;
if (parent[e.to] != v) continue;
acc = merge(acc, add_edge(down[e.to], e));
}
down[v] = add_vertex(acc, v);
}
for (int v : order) {
int d = int(g[v].size());
std::vector<DP> contrib(d, id);
for (int i = 0; i < d; i++) {
const auto& e = g[v][i];
if (!e.alive) continue;
if (parent[e.to] == v) {
contrib[i] = add_edge(down[e.to], e);
} else if (parent[v] == e.to && parent_edge[v] == e.id) {
contrib[i] = add_edge(outside[v], e);
}
}
std::vector<DP> pref(d + 1, id), suff(d + 1, id);
for (int i = 0; i < d; i++) pref[i + 1] = merge(pref[i], contrib[i]);
for (int i = d - 1; i >= 0; i--) suff[i] = merge(contrib[i], suff[i + 1]);
answer[v] = add_vertex(pref[d], v);
for (int i = 0; i < d; i++) {
const auto& e = g[v][i];
if (!e.alive) continue;
if (parent[e.to] != v) continue;
outside[e.to] = add_vertex(merge(pref[i], suff[i + 1]), v);
}
}
return answer;
}
} // namespace tree
} // namespace m1une