Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions content/graphs/Reroot.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Author: Nic Washbourne
* Date: 2025-09-26
* Source: Sachin Sivakumar
* Description: Generic reroot DP with decombine. The provided operations solve sum of distances to all nodes.
* Time: O(N)
* Status: Tested on CSES: Tree Distances II
*/
#pragma once

using T = pair<ll, ll>;
T init() { return {1, 0}; }
T combine(T a, T b) { return {a.first + b.first,
a.second + b.second + b.first}; }
T decombine(T a, T b) { return {a.first - b.first,
a.second - b.second - b.first}; }

vector<vi> adj;
vector<T> dp, dpr;

T dfs(int u, int p) {
dp[u] = init();
for (int v : adj[u]) if (v != p)
dp[u] = combine(dp[u], dfs(v, u));
return dp[u];
}

T dfsr(int u, int p, T dpr_p = init()) {
dpr[u] = dp[u];
if (p != u) dpr[u] = combine(dpr[u], dpr_p);
for (int v : adj[u]) if (v != p)
dfsr(v, u, decombine(dpr[u], dp[v]));
return dpr[u];
}
1 change: 1 addition & 0 deletions content/graphs/chapter.tex
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ \section{DFS algorithms}
\kactlimport{2sat.h}
\kactlimport{EulerWalk.h}
\kactlimport{DominatorTree.h}
\kactlimport{Reroot.h}

\section{Coloring}
\kactlimport{EdgeColoring.h}
Expand Down