Kyopro Library
 
読み取り中…
検索中…
一致する文字列を見つけられません
centroid.hpp
[詳解]
1#include"../../../kyopro_library/template.hpp"
2
3
4/**
5 * @brief 重心分解
6 * @param seen 探索済みフラグ
7 * @param sz 各頂点の部分木のサイズ
8 *
9 * ```cpp
10 * vector<int> sz(N);
11 * vector<bool> seen(N);
12 *
13 * auto centroid_decomposition = [&](auto self, int root) -> void {
14 * int centroid = TreeCentroid(g, root, seen, sz);
15 * seen[centroid] = true;
16 *
17 * // ここに処理を書く
18 *
19 * for (int nxt : g[centroid]) {
20 * if (seen[nxt]) continue;
21 * self(self, nxt);
22 * }
23 * };
24 * centroid_decomposition(centroid_decomposition, 0);
25 * ```
26 */
27int TreeCentroid(const vector<vector<int>>& g, int root, vector<int>& seen, vector<int>& sz) {
28 int n=g.size();
29 if(sz.empty()) sz=vector<int>(n);
30 if(seen.empty()) seen=vector<int>(n,false);
31
32 auto dfs=[&](auto dfs, int now, int pre)-> int {
33 sz[now]=1;
34 for(int nxt: g[now]) {
35 if(nxt==pre||seen[nxt]) continue;
36 sz[now]+=dfs(dfs,nxt,now);
37 }
38 return sz[now];
39 };
40
41 int total=dfs(dfs,root,-1);
42 int centroid=root;
43
44 auto dfs2=[&](auto dfs2, int now, int pre)-> void {
45 bool ok=(total-sz[now])*2<=total;
46 for(int nxt: g[now]) {
47 if(nxt==pre||seen[nxt]) continue;
48 dfs2(dfs2,nxt,now);
49 if(sz[nxt]*2>total) ok=false;
50 }
51 if(ok) centroid=now;
52 };
53 dfs2(dfs2,root,-1);
54
55 return centroid;
56}
int TreeCentroid(const vector< vector< int > > &g, int root, vector< int > &seen, vector< int > &sz)
重心分解
Definition centroid.hpp:27