forked from Ashishgup1/Competitive-Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCentroid Decomposition.cpp
More file actions
49 lines (42 loc) · 852 Bytes
/
Centroid Decomposition.cpp
File metadata and controls
49 lines (42 loc) · 852 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
int nodes = 0;
int subtree[N], parentcentroid[N];
set<int> g[N];
void dfs(int u, int par)
{
nodes++;
subtree[u] = 1;
for(auto &it:g[u])
{
if(it == par)
continue;
dfs(it, u);
subtree[u] += subtree[it];
}
}
int centroid(int u, int par)
{
for(auto &it:g[u])
{
if(it == par)
continue;
if(subtree[u] > (nodes >> 1))
return centroid(it,u);
}
return u;
}
void decompose(int u, int par)
{
nodes = 0;
dfs(u, u);
int node = centroid(u, u);
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 (Same as above, with colors being reverted): https://www.spoj.com/problems/QTREE5/
//Problem 3: https://codeforces.com/contest/342/problem/E