-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcentroid_decomp.cpp
More file actions
38 lines (36 loc) · 829 Bytes
/
centroid_decomp.cpp
File metadata and controls
38 lines (36 loc) · 829 Bytes
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
// Template for centroid decomposition
// Note: this does not include distances
// Author: Dan Shan
#include <bits/stdc++.h>
using namespace std;
const int MM = 1e5+2;
vector<int> adj[MM], adj2[MM];
int sz[MM];
bool cent[MM];
void dfs(int s, int p){
sz[s]=1;
for(auto x: adj[s]){
if(x==p||cent[x]) continue; // ignore parent && centroids
dfs(x,s);
sz[s]+=sz[x];
}
}
int fc(int s, int p, int n){
for(auto x: adj[s]){
if(x==p||cent[x]) continue;
if(sz[x]>n/2) return fc(x,s,n);
}
return s;
}
int decomp(int root){
dfs(root,-1);
int cen = fc(root,-1,sz[1]);
cent[cen]=1;
for(auto x: adj[cen]){
if(cent[x]) continue;
int sub=decomp(x);
adj2[cen].emplace_back(sub);
adj2[sub].emplace_back(cen);
}
return cen;
}