-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCentroid Decomposition structure.cpp
More file actions
49 lines (41 loc) · 1.01 KB
/
Centroid Decomposition structure.cpp
File metadata and controls
49 lines (41 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
struct CentroidDecomposition
{
vector <set <int>> g;
vi parent, sz;
CentroidDecomposition(vector <set <int>> &_g): g(_g)
{
int n = g.size();
parent.resize(n);
sz.resize(n);
Build(0, -1);
}
void Build(int x, int p)
{
int n = findSz(x, p);
int centroid = findCentroid(x, p, n);
if (p == -1) p = centroid;
parent[centroid] = p;
set <int>::iterator it = g[centroid].begin();
for (; !g[centroid].empty();)
{
int y = *it;
g[centroid].erase(it);
g[y].erase(centroid);
Build(y, centroid);
it = g[centroid].begin();
}
}
int findSz(int x, int p)
{
sz[x] = 1;
for (auto y: g[x])
if (y != p) sz[x] += findSz(y, x);
return sz[x];
}
int findCentroid(int x, int p, int n)
{
for (auto y: g[x])
if (y != p && sz[y] > n/2) return findCentroid(y, x, n);
return x;
}
};