競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
CentroidDecompositionは、無向木を重心で分割し、O(log(N+1))段の重心木を作ります。頂点への印付けと最寄りの印の照会などに使えます。本体・使用例を参照してください。
CentroidDecompositionCentroidDecomposition();
explicit CentroidDecomposition(const Graph& graph, bool store_distances = true);
CentroidDecomposition(const CentroidDecomposition&);
CentroidDecomposition(CentroidDecomposition&& other) noexcept;
無向木の重心分解を作ります。store_distances=trueなら元の木での距離情報も保存します。
制約: 頂点数・入力構造・型の前提を満たすこと。空の構築も可能です。
計算量: 空の構築・ムーブはO(1)、コピーは保持領域に比例。木からはO(N log(N+1))時間、保持領域は距離ありO(N log(N+1))、距離なしO(N)。
buildvoid build(const Graph& graph, bool store_distances = true);
分解を構築/再構築する。入力を変更・保持しない。
制約: 入力グラフ・関数・比較器の前提は下記の共通条件に従います。
計算量: O(N log(N+1))時間。距離ありは同じ保持領域、距離なしはO(N)保持領域。
rootint root() const noexcept;
根の頂点番号を返します。空なら-1です。
制約: なし。
計算量: O(1)。
parentint parent(int vertex) const;
親の頂点番号を返します。根の親は-1です。
制約: 引数の頂点番号・添字は有効範囲内です。その他の前提は共通条件に従います。
計算量: O(1)。
depthint depth(int vertex) const;
根からの深さを返します。
制約: 引数の頂点番号・添字は有効範囲内です。その他の前提は共通条件に従います。
計算量: O(1)。
component_sizeint component_size(int vertex) const;
vを重心として除去した時点の成分サイズを返します。
制約: 引数の頂点番号・添字は有効範囲内です。その他の前提は共通条件に従います。
計算量: O(1)。
ancestorsconst std::vector<Ancestor>& ancestors(int vertex) const;
重心木の根からvまでのAncestor列をconst参照で返します。最後の要素は{v,0}です。
制約: 距離情報を保存して構築済みで、頂点番号が有効であること。
計算量: O(1)。
distancestd::int64_t distance(int u, int v) const;
元の木の辺数距離をstd::int64_tで返す。
制約: 距離情報を保存して構築済みで、頂点番号が有効であること。
計算量: O(log(N+1))。
parentsconst std::vector<int>& parents() const noexcept;
親番号の配列を読み取り専用で返します。
制約: なし。
計算量: O(1)。
depthsconst std::vector<int>& depths() const noexcept;
深さの配列を読み取り専用で返します。
制約: なし。
計算量: O(1)。
orderconst std::vector<int>& order() const noexcept;
構築時に得た頂点の順序を読み取り専用で返します。
制約: なし。
計算量: O(1)。
centroid_treeGraph centroid_tree() const;
重心木の無向隣接リストを独立した値として返します。
制約: なし。
計算量: O(N)時間・領域。
sizestd::size_t size() const noexcept;
頂点数を返します。
制約: なし。
計算量: O(1)。
emptybool empty() const noexcept;
頂点数が0ならtrueを返します。
制約: なし。
計算量: O(1)。
stores_distancesbool stores_distances() const noexcept;
元の木での距離情報を保持していればtrueを返します。
制約: なし。
計算量: O(1)。
clearvoid clear() noexcept;
領域を解放して空の状態へ戻します。
制約: なし。
計算量: 保持領域の解放に比例します。
swapvoid swap(CentroidDecomposition& other) noexcept;
void swap(CentroidDecomposition& a, CentroidDecomposition& b) noexcept;
保持するグラフ・結果・状態を交換します。
制約: なし。
計算量: O(1)。
Graph graph{{1}, {0,2}, {1,3}, {2}};
CentroidDecomposition decomposition(graph);
auto distance = decomposition.distance(0,3); // 3。
for (auto a : decomposition.ancestors(3)) {
// a.vertexは祖先の重心、a.distanceは元の木での3からの距離。
}
Ancestorは{vertex,distance}です。距離には元の木での辺数を使い、各祖先列の長さはO(log(N+1))です。印の追加や最寄りの印の照会に使う場合は、完全な使用例を参照してください。
既定では距離情報も構築し、O(N log(N+1))時間・領域です。CentroidDecomposition(graph,false)またはbuild(graph,false)なら距離を保存せず、領域O(N)です。この場合ancestors・distanceは使えません。distanceはO(log(N+1))、centroid_treeはO(N)、結果配列の参照・単点取得はO(1)です。
頂点0..N-1の単純無向木が前提です。空の木も許します。入力は構築後に破棄・変更できます。
コピーは独立、move元は空、swapはO(1)です。コピー代入・buildに失敗した場合は旧結果を維持します。結果への参照は再構築・代入・clear・破棄まで有効です。
既定では初回の成分探索に、頂点番号・循環・到達頂点数・逆向きの辺の検査を組み込みます。検査専用の全辺走査や、後の成分での繰り返し検査はしません。SKIP_RUNTIME_CHECKSでこれらと頂点・距離保存の検査を除き、頂点数の表現上限は維持します。
数学的参考はNyaan、機能上の参考はLuzhiledです。入力を保持しない反復構築として独立に記述しています。
CentroidDecomposition::Ancestor::operator==bool operator==(const Ancestor&, const Ancestor&);
祖先頂点と距離の両フィールドが一致すればtrueを返します。
制約: なし。
計算量: O(1)。
operator=CentroidDecomposition& operator=(const CentroidDecomposition& other);
CentroidDecomposition& operator=(CentroidDecomposition&& other) noexcept;
コピー/ムーブ代入し、自身への参照を返します。
制約: なし。
計算量: コピーは保持領域に比例します。旧状態の破棄費用を加えます。
Graph: vector<vector<int>>。頂点0..n-1の単純無向木。n=0も扱う。入力は変更・保持しない。
CentroidDecomposition()/CentroidDecomposition(graph,store_distances=true): 空/重心分解を構築。
build(graph,store_distances=true): 再構築、失敗時は元の結果を維持。時間O(n log(n+1))。
距離を保存する場合は領域O(n log(n+1))、省く場合はO(n)。全探索を反復で行う。
size()/empty()/root()/stores_distances(): 頂点数/空か/重心木の根(空なら-1)/距離保存の有無、O(1)。
parent(v)/depth(v)/component_size(v): 重心木の親(根は-1)/深さ/除去時の成分サイズ、O(1)。
parents()/depths()/order(): 親配列/深さ配列/親が先に現れる重心列へのconst参照、O(1)。
Ancestor{int vertex; int distance;}: 祖先重心と元の木における辺数距離。
ancestors(v): 重心木の根からvまでのAncestor列へのconst参照、O(1)。距離保存時だけ使う。
distance(u,v): 元の木の距離をint64_tで返す、O(log(n+1))。距離保存が前提。
centroid_tree(): 重心木の無向隣接リストを所有値で返す、O(n)。
clear()/swap(other): 空にする/交換する。clearは格納要素数に比例、swapはO(1)。
コピーは独立。move元は空。build/clear/代入により、以前の配列参照は無効となる。
SKIP_RUNTIME_CHECKSで頂点・距離保存・初回の探索に組み込んだ木の入力検査を除く。
入力検査のためだけの全辺走査はしない。頂点数の表現上限は省略しない。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| Balanced Tree | centroid_decomposition.cpp | 未提出 | — |
| Submit Your Solution | virtual_tree_distance_product.cpp | 未提出 | — |
✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。
| 検査 | 状態 |
|---|---|
| 正常系 | 未実施 |
| 失敗系 | 未測定 |
| Library Checker公式ケース | 無し |
| 性能測定 | 未実施 |
| ASan/UBSan | 未実施 |
| カバレッジ | 未実施 |
到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。
// SPDX-License-Identifier: CC0-1.0
// 数学的参考: https://nyaannyaan.github.io/library/tree/centroid-decomposition.hpp.html
// 参考: https://ei1333.github.io/library/graph/tree/centroid-decomposition.hpp.html
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/centroid_decomposition.md
//
// API一覧
// Graph: vector<vector<int>>。頂点0..n-1の単純無向木。n=0も扱う。入力は変更・保持しない。
// CentroidDecomposition()/CentroidDecomposition(graph,store_distances=true): 空/重心分解を構築。
// build(graph,store_distances=true): 再構築、失敗時は元の結果を維持。時間O(n log(n+1))。
// 距離を保存する場合は領域O(n log(n+1))、省く場合はO(n)。全探索を反復で行う。
// size()/empty()/root()/stores_distances(): 頂点数/空か/重心木の根(空なら-1)/距離保存の有無、O(1)。
// parent(v)/depth(v)/component_size(v): 重心木の親(根は-1)/深さ/除去時の成分サイズ、O(1)。
// parents()/depths()/order(): 親配列/深さ配列/親が先に現れる重心列へのconst参照、O(1)。
// Ancestor{int vertex; int distance;}: 祖先重心と元の木における辺数距離。
// ancestors(v): 重心木の根からvまでのAncestor列へのconst参照、O(1)。距離保存時だけ使う。
// distance(u,v): 元の木の距離をint64_tで返す、O(log(n+1))。距離保存が前提。
// centroid_tree(): 重心木の無向隣接リストを所有値で返す、O(n)。
// clear()/swap(other): 空にする/交換する。clearは格納要素数に比例、swapはO(1)。
// コピーは独立。move元は空。build/clear/代入により、以前の配列参照は無効となる。
// SKIP_RUNTIME_CHECKSで頂点・距離保存・初回の探索に組み込んだ木の入力検査を除く。
// 入力検査のためだけの全辺走査はしない。頂点数の表現上限は省略しない。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <stdexcept>
#include <utility>
#include <vector>
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_UNWEIGHTED_GRAPH_DEFINED
#define SIRKIT_UNWEIGHTED_GRAPH_DEFINED
using Graph = std::vector<std::vector<int>>;
#endif
#ifndef SIRKIT_CENTROID_DECOMPOSITION_DEFINED
#define SIRKIT_CENTROID_DECOMPOSITION_DEFINED
namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ {
inline void CheckCentroidVertexCount(std::size_t vertices) {
if (vertices > static_cast<std::size_t>(std::numeric_limits<int>::max()))
throw std::length_error("CentroidDecomposition vertex count");
}
}
class CentroidDecomposition {
public:
struct Ancestor {
int vertex;
int distance;
friend bool operator==(const Ancestor&, const Ancestor&) = default;
};
private:
int root_ = -1;
bool stores_distances_ = false;
std::vector<int> parent_, depth_, component_size_, order_;
std::vector<std::vector<Ancestor>> ancestors_;
void check_vertex(int vertex) const {
#ifndef SKIP_RUNTIME_CHECKS
if (vertex < 0 || static_cast<std::size_t>(vertex) >= size())
throw std::out_of_range("CentroidDecomposition vertex");
#else
static_cast<void>(vertex);
#endif
}
void check_distances() const {
#ifndef SKIP_RUNTIME_CHECKS
if (!stores_distances_) throw std::logic_error("CentroidDecomposition distances not stored");
#endif
}
void initialize(const Graph& graph, bool store_distances) {
const auto n = graph.size();
/*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::CheckCentroidVertexCount(n);
stores_distances_ = store_distances;
parent_.assign(n, -1); depth_.resize(n); component_size_.resize(n); order_.reserve(n);
if (store_distances) ancestors_.resize(n);
if (n == 0) return;
std::vector<unsigned char> removed(n);
std::vector<int> traversal_parent(n, -2), subtree(n), component;
std::vector<std::pair<int,int>> pending{{0,-1}};
struct Visit { int vertex, parent, distance; };
std::vector<Visit> visits;
component.reserve(n);
while (!pending.empty()) {
const auto [start, above] = pending.back(); pending.pop_back();
#ifndef SKIP_RUNTIME_CHECKS
const bool validate = above == -1;
#endif
component.clear(); component.push_back(start);
traversal_parent[static_cast<std::size_t>(start)] = -1;
for (std::size_t i = 0; i < component.size(); ++i) {
const int vertex = component[i];
subtree[static_cast<std::size_t>(vertex)] = 1;
#ifndef SKIP_RUNTIME_CHECKS
std::size_t parent_edges = 0;
#endif
for (const int to : graph[static_cast<std::size_t>(vertex)]) {
#ifndef SKIP_RUNTIME_CHECKS
if (validate && (to < 0 || static_cast<std::size_t>(to) >= n || to == vertex))
throw std::invalid_argument("CentroidDecomposition tree edge");
#endif
if (to == traversal_parent[static_cast<std::size_t>(vertex)]) {
#ifndef SKIP_RUNTIME_CHECKS
if (validate) ++parent_edges;
#endif
continue;
}
if (removed[static_cast<std::size_t>(to)]) continue;
#ifndef SKIP_RUNTIME_CHECKS
if (validate && traversal_parent[static_cast<std::size_t>(to)] != -2)
throw std::invalid_argument("CentroidDecomposition input is not a tree");
#endif
traversal_parent[static_cast<std::size_t>(to)] = vertex;
component.push_back(to);
}
#ifndef SKIP_RUNTIME_CHECKS
if (validate && vertex != start && parent_edges != 1)
throw std::invalid_argument("CentroidDecomposition asymmetric tree");
#endif
}
#ifndef SKIP_RUNTIME_CHECKS
if (validate && component.size() != n)
throw std::invalid_argument("CentroidDecomposition disconnected tree");
#endif
for (auto it = component.rbegin(); it != component.rend(); ++it) {
const int above_vertex = traversal_parent[static_cast<std::size_t>(*it)];
if (above_vertex != -1)
subtree[static_cast<std::size_t>(above_vertex)] += subtree[static_cast<std::size_t>(*it)];
}
const int count = static_cast<int>(component.size());
int centroid = start;
for (;;) {
int next = -1;
for (const int to : graph[static_cast<std::size_t>(centroid)]) {
if (!removed[static_cast<std::size_t>(to)] &&
traversal_parent[static_cast<std::size_t>(to)] == centroid &&
subtree[static_cast<std::size_t>(to)] > count / 2) { next = to; break; }
}
if (next == -1) break;
centroid = next;
}
parent_[static_cast<std::size_t>(centroid)] = above;
depth_[static_cast<std::size_t>(centroid)] = above == -1 ? 0 : depth_[static_cast<std::size_t>(above)] + 1;
component_size_[static_cast<std::size_t>(centroid)] = count;
order_.push_back(centroid);
if (above == -1) root_ = centroid;
if (store_distances) {
visits.clear(); visits.push_back({centroid, -1, 0});
for (std::size_t i = 0; i < visits.size(); ++i) {
const auto [vertex, from, distance] = visits[i];
ancestors_[static_cast<std::size_t>(vertex)].push_back({centroid, distance});
for (const int to : graph[static_cast<std::size_t>(vertex)])
if (to != from && !removed[static_cast<std::size_t>(to)])
visits.push_back({to, vertex, distance + 1});
}
}
removed[static_cast<std::size_t>(centroid)] = 1;
for (const int to : graph[static_cast<std::size_t>(centroid)])
if (!removed[static_cast<std::size_t>(to)]) pending.emplace_back(to, centroid);
}
}
public:
CentroidDecomposition() = default;
explicit CentroidDecomposition(const Graph& graph, bool store_distances = true) { initialize(graph, store_distances); }
CentroidDecomposition(const CentroidDecomposition&) = default;
CentroidDecomposition& operator=(const CentroidDecomposition& other) {
if (this != &other) { CentroidDecomposition next(other); swap(next); }
return *this;
}
CentroidDecomposition(CentroidDecomposition&& other) noexcept { swap(other); }
CentroidDecomposition& operator=(CentroidDecomposition&& other) noexcept {
CentroidDecomposition next(std::move(other)); swap(next); return *this;
}
void swap(CentroidDecomposition& other) noexcept {
std::swap(root_, other.root_); std::swap(stores_distances_, other.stores_distances_);
parent_.swap(other.parent_); depth_.swap(other.depth_); component_size_.swap(other.component_size_);
order_.swap(other.order_); ancestors_.swap(other.ancestors_);
}
friend void swap(CentroidDecomposition& a, CentroidDecomposition& b) noexcept { a.swap(b); }
void build(const Graph& graph, bool store_distances = true) {
CentroidDecomposition next(graph, store_distances); swap(next);
}
void clear() noexcept {
root_ = -1; stores_distances_ = false;
parent_.clear(); depth_.clear(); component_size_.clear(); order_.clear(); ancestors_.clear();
}
std::size_t size() const noexcept { return parent_.size(); }
bool empty() const noexcept { return parent_.empty(); }
int root() const noexcept { return root_; }
bool stores_distances() const noexcept { return stores_distances_; }
int parent(int vertex) const { check_vertex(vertex); return parent_[static_cast<std::size_t>(vertex)]; }
int depth(int vertex) const { check_vertex(vertex); return depth_[static_cast<std::size_t>(vertex)]; }
int component_size(int vertex) const { check_vertex(vertex); return component_size_[static_cast<std::size_t>(vertex)]; }
const std::vector<int>& parents() const noexcept { return parent_; }
const std::vector<int>& depths() const noexcept { return depth_; }
const std::vector<int>& order() const noexcept { return order_; }
const std::vector<Ancestor>& ancestors(int vertex) const {
check_vertex(vertex); check_distances(); return ancestors_[static_cast<std::size_t>(vertex)];
}
std::int64_t distance(int u, int v) const {
const auto& a = ancestors(u); const auto& b = ancestors(v);
std::size_t i = 0;
while (i < a.size() && i < b.size() && a[i].vertex == b[i].vertex) ++i;
return static_cast<std::int64_t>(a[i - 1].distance) + b[i - 1].distance;
}
Graph centroid_tree() const {
Graph result(size());
for (std::size_t vertex = 0; vertex < size(); ++vertex) {
const int above = parent_[vertex];
if (above != -1) {
result[vertex].push_back(above);
result[static_cast<std::size_t>(above)].push_back(static_cast<int>(vertex));
}
}
return result;
}
};
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1