Skip to content

Commit 0ea61bb

Browse files
authored
feat: centroid decomposition was added
1 parent 1f05969 commit 0ea61bb

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// const int N = @@;
2+
// int n;
3+
// vector<int> adj[N];
4+
5+
namespace decomposition {
6+
int subtree[N], depth[N], f[N];
7+
8+
int dfs(int u, int p = -1) {
9+
subtree[u] = 1;
10+
for(const auto &v: adj[u])
11+
if(v != p)
12+
subtree[u] += dfs(v, u);
13+
return subtree[u];
14+
}
15+
16+
int get_centroid(int u, int sz, int p = -1) {
17+
for(const auto &v: adj[u])
18+
if(!depth[v] && v != p && subtree[v] > sz)
19+
return get_centroid(v, sz, u);
20+
return u;
21+
}
22+
23+
int decompose(int u, int d=1) {
24+
int centroid = get_centroid(u, dfs(u) / 2);
25+
depth[u] = d;
26+
for(const auto &v: adj[u])
27+
if(!depth[v])
28+
f[decompose(v, d + 1)] = centroid;
29+
return centroid;
30+
}
31+
32+
int lca(int u, int v) {
33+
for(; u != v; u = f[u])
34+
if(depth[v] > depth[u])
35+
swap(u, v);
36+
return u;
37+
}
38+
39+
void clean(int n) {
40+
for(int i = 0; i < n; ++i){
41+
subtree[i] = 0;
42+
depth[i] = 0;
43+
f[i] = 0;
44+
}
45+
}
46+
47+
vector<int> get_centroids() {
48+
vector<int> centroids;
49+
// clean(n);
50+
dfs(0);
51+
int centroid = get_centroid(0, n / 2);
52+
centroids.push_back(centroid);
53+
clean(n);
54+
dfs(centroid);
55+
for(const auto &v: adj[centroid]) {
56+
if((subtree[centroid] - subtree[v]) == n / 2) {
57+
centroids.push_back(v);
58+
}
59+
}
60+
assert(0 < (int) centroids.size() && (int) centroids.size() <= 2);
61+
return centroids;
62+
}
63+
}
64+
65+
using namespace decomposition;

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy