Dsu On Tree
Dsu On Tree
vector<int>g[N];
vector<int>v[N];// store all the node which are in the subtree of s
int sz[N];
int cnt[N];//cnt[i] is count of node in subtree whose color is i
int color[N];
void getsz(int s, int p)
{
sz[s]=1;
for(auto u:g[s])
{
if(u==p)
continue;
getsz(u, s);
sz[s]+=sz[u];
}
}
//keep==1 we are in bigChild
//keep==0 we are in smallChild
void dfs(int s, int p, bool keep) {
if (bigchild != -1) {
dfs(bigchild, s, 1);
// at this moment the cnt[N] array store the data of BigChild
// which is reuse in the calculation of subtree s(same for v)
//so we just swap the data.
swap(v[s], v[bigchild]);
}
v[s].push_back(s);
cnt[color[s]]++;
//to get data from small subtree we just iterate through node
for (auto u : g[s]) {
if (u != p && u != bigchild) {
for (auto x : v[u]) {
cnt[color[x]]++;
v[s].push_back(x);
}
}
}
// now for the subtree s cnt[i] array store the number of node with color i
//v[s] store all the elemnet in the subtree of s.
// if the keep=1 then this data is being use in the calculation of the parent
ans
//But for keep=0 we have to erase data from cnt array.
if (keep == 0) {
for (auto u : v[s]) {
cnt[color[u]]--;
}
}
}