forked from Ashishgup1/Competitive-Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCentroid Decomposition
More file actions
47 lines (41 loc) · 781 Bytes
/
Centroid Decomposition
File metadata and controls
47 lines (41 loc) · 781 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
int subtree[N], parentcentroid[N];
set<int> g[N];
void dfs(int k, int par)
{
nodes++;
subtree[k]=1;
for(auto it:g[k])
{
if(it==par)
continue;
dfs(it, k);
subtree[k]+=subtree[it];
}
}
int centroid(int k, int par)
{
for(auto it:g[k])
{
if(it==par)
continue;
if(subtree[it]>(nodes>>1))
return centroid(it, k);
}
return k;
}
void decompose(int k, int par)
{
nodes=0;
dfs(k, k);
int node=centroid(k, k);
parentcentroid[node]=par;
for(auto it:g[node])
{
g[it].erase(node);
decompose(it, node);
}
}
//Problem 1: https://codeforces.com/contest/322/problem/E
//Solution 1: https://codeforces.com/contest/322/submission/45791742
//Problem 2: https://codeforces.com/contest/342/problem/E
//Solution 2: https://codeforces.com/contest/342/problem/E