diff --git a/content/graphs/Reroot.h b/content/graphs/Reroot.h new file mode 100644 index 000000000..509262faa --- /dev/null +++ b/content/graphs/Reroot.h @@ -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; +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 adj; +vector 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]; +} diff --git a/content/graphs/chapter.tex b/content/graphs/chapter.tex index 72815a718..db4a53742 100644 --- a/content/graphs/chapter.tex +++ b/content/graphs/chapter.tex @@ -29,6 +29,7 @@ \section{DFS algorithms} \kactlimport{2sat.h} \kactlimport{EulerWalk.h} \kactlimport{DominatorTree.h} + \kactlimport{Reroot.h} \section{Coloring} \kactlimport{EdgeColoring.h}