With dsu on tree we can answer queries of this type:
How many vertices in subtree of vertex v has some property in O(n lg n) time (for all of the queries).
For example:
Given a tree, every vertex has color. Query is how many vertices in subtree of vertex v are colored with color c?
要点:记录每棵子树的大小,启发式合并。
模板整理如下:
1. easy to code but
1 //O(nlognlogn) 2 map<int, int> *cnt[maxn]; 3 void dfs(int v, int p){ 4 int mx = -1, bigChild = -1; 5 for(auto u : g[v]) 6 if(u != p){ 7 dfs(u, v); 8 if(sz[u] > mx) 9 mx = sz[u], bigChild = u; 10 } 11 if(bigChild != -1) 12 cnt[v] = cnt[bigChild]; 13 else 14 cnt[v] = new map<int, int> (); 15 (*cnt[v])[ col[v] ] ++; 16 for(auto u : g[v]) 17 if(u != p && u != bigChild){ 18 for(auto x : *cnt[u]) 19 (*cnt[v])[x.first] += x.second; 20 } 21 //now (*cnt)[c] is the number of vertices in subtree of vertex v that has color c. You can answer the queries easily. 22 23 }