-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcentroid_decomp.cpp
More file actions
54 lines (43 loc) · 909 Bytes
/
centroid_decomp.cpp
File metadata and controls
54 lines (43 loc) · 909 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5;
int n;
vector<int>adj[maxn+13];
int size[maxn+13] = {};
int dad[maxn+13] = {};
bool removed[maxn+13] = {};
void dfs(int a, int p){
size[a] = 1;
for(int b:adj[a]){
if (b == p || removed[b]) continue;
dfs(b, a);
size[a] += size[b];
}
}
int centroid(int a, int p, int m){
for(int b:adj[a]){
if (b == p || removed[b]) continue;
if (size[b]*2 > m) return centroid(b, a, m);
}
return a;
}
void build(int a, int p){
dfs(a, -1);
a = centroid(a, -1, size[a]);
dad[a] = p;
removed[a] = true;
for(int b:adj[a]){
if (removed[b]) continue;
build(b, a);
}
}
int main(){
cin>>n;
for(int i = 0;i < n-1;i++){
int a, b;cin>>a>>b;
adj[a].push_back(b);
adj[b].push_back(a);
}
build(1, -1);
return 0;
}