templates/centroid-decomposition.cpp
compilable
$cat templates/centroid-decomposition
Centroid Decomposition
Divide-and-conquer on trees via centroid selection for O(n log n) path processing.
#centroid#decomposition#tree#divide-and-conquer
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 5;
vector<int> adj[MAXN];
int sz[MAXN];
bool removed[MAXN];
int getSize(int u, int p) {
sz[u] = 1;
for (int v : adj[u])
if (v != p && !removed[v])
sz[u] += getSize(v, u);
return sz[u];
}
int getCentroid(int u, int p, int total) {
for (int v : adj[u])
if (v != p && !removed[v] && sz[v] * 2 > total)
return getCentroid(v, u, total);
return u;
}
void decompose(int u) {
int c = getCentroid(u, -1, getSize(u, -1));
removed[c] = true;
// process all paths through centroid c here
for (int v : adj[c])
if (!removed[v]) decompose(v);
}32 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Centroid Decomposition
Recursively split a tree at its centroid — a node whose largest subtree has nodes. The resulting decomposition tree has height .
How It Works
When to Use
Notes
decompose() is a skeleton — add your path-processing logic after finding the centroid