摘自Codeforces博客

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 DSU模板(树的启发式合并)

 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 }
View Code

相关文章:

  • 2021-07-21
  • 2021-04-25
  • 2022-12-23
  • 2023-03-18
  • 2021-08-07
  • 2020-10-08
  • 2022-12-23
猜你喜欢
  • 2021-06-15
  • 2022-12-23
  • 2022-12-23
  • 2021-08-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案