ContinueLib

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub Continue765/ContinueLib

:heavy_check_mark: centroidDecompsition
(graph/tree/centroid.hpp)

centroidDecompsition

定义于头文件 centroid.hpp

template <typename T, typename F>
void centroidDecompsition(const Tree<T>& tree, F&& f);

对 tree 做点分治,每确定一个重心就以该重心的分治块为参数调用一次 f(fa, vt, pos),总计 $O(n \log n)$。

参数

参数 说明
tree 树
f 回调,对每个重心调用 f(fa, vt, pos),三个参数均为 vector<int>

回调参数

参数 说明
vt 当前分治块内的点,局部编号从 $0$ 开始,编号 $0$ 为重心
fa fa[i] 为 vt[i] 的父节点局部编号,fa[0] = -1
pos 以重心为根的各分支在 vt 中的边界:pos[0] = 0,pos[1] = 1,第 $j$ 个分支(从 $0$ 起)占区间 $[\text{pos}[j+1], \text{pos}[j+2])$

示例

Undigraph<int> g(n);
g.add(0, 1);
g.add(1, 2);

Tree<int> tree(g);
vector<int> cen;
centroidDecompsition(tree, [&](vector<int>& fa, vector<int>& vt, vector<int>& pos) {
    cen.push_back(vt[0]);
});

Depends on

Required by

Verified with

Code

#pragma once
#include <graph/tree/tree.hpp>

// f(fa, vt, pos),局部编号 0 为重心,各分支占连续区间。
template <typename T, typename F>
void centroidDecompsition(const Tree<T>& tree, F&& f) {
    const auto& g = tree.g;
    vector<int> dead(tree.n), siz, fa, vt, pos;
    auto collect = [&](int u, int p) {
        int l = vt.size();
        vt.push_back(u);
        fa.push_back(p);
        for (int i = l; i < int(vt.size()); i++) {
            int u = vt[i];
            for (auto [v, id] : g[u]) {
                if (dead[v] || (fa[i] != -1 && v == vt[fa[i]])) {
                    continue;
                }
                vt.push_back(v);
                fa.push_back(i);
            }
        }
    };
    vector<int> rts{tree.root};
    for (int t = 0; t < int(rts.size()); t++) {
        vt.clear();
        fa.clear();
        collect(rts[t], -1);
        int m = vt.size(), c = -1;
        siz.assign(m, 1);
        for (int i = m - 1; i >= 0; i--) {
            if (siz[i] >= (m + 1) / 2) {
                c = vt[i];
                break;
            }
            siz[fa[i]] += siz[i];
        }
        dead[c] = true;
        vt = {c};
        fa = {-1};
        pos = {0, 1};
        for (auto [v, id] : g[c]) {
            if (!dead[v]) {
                rts.push_back(v);
                collect(v, 0);
                pos.push_back(vt.size());
            }
        }
        f(fa, vt, pos);
    }
}
Back to top page