競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
各頂点から出る辺が1本の有向グラフを分解します。頂点は0..N-1です。自己辺、複数の周期、周期へ合流する木を扱います。各弱連結成分は有向周期を1つ持ちます。
FunctionalGraphFunctionalGraph();
explicit FunctionalGraph(std::span<const int> successors);
FunctionalGraph(const FunctionalGraph&);
FunctionalGraph(FunctionalGraph&& other) noexcept;
引数を省略すると空のグラフを作り、行先の配列を渡すとその配列から構築します。行先はグラフがコピーして所有するため、構築後に入力は参照しません。
制約: 全ての行先は0..N-1。空列も可。
計算量: 空の構築O(1)、列からの構築・コピーO(N log(N+1))時間・領域、ムーブO(1)。
buildvoid build(std::span<const int> successors);
行先配列から再構築します。自身のsuccessors()を入力にしても構いません。
制約: 全ての行先は0..N-1。
計算量: O(N log(N+1))時間・領域。旧状態の破棄費用も加わります。
kth_successorint kth_successor(int v, std::uint64_t k) const;
vからk本の辺を進んだ頂点を返します。k=0はvです。
制約: 0<=v<N。kはstd::uint64_t全域を扱います。
計算量: O(log(N+1))。
distancestd::int64_t distance(int from, int to) const;
fromからtoへ初めて到達する辺数を返します。到達不能は-1、自身へは0です。
制約: from,toは有効な頂点番号。
計算量: O(log(N+1))。
reachablebool reachable(int from, int to) const;
fromからtoへ到達可能ならtrueを返します。同じ弱連結成分でも到達不能な場合があります。
制約: from,toは有効な頂点番号。
計算量: O(log(N+1))。
infoCycleInfo info(int v) const;
CycleInfo{id,entry,depth,position,length}を返します。idは到達する周期の番号、entryはその周期で最初に到達する頂点、depthはそこまでの辺数です。positionは周期内でのentryの添字、lengthは周期の長さです。
制約: 0<=v<N。
計算量: O(1)。
cyclestd::span<const int> cycle(int id) const;
successor方向に並ぶ周期頂点への読み取り専用spanを返します。周期の始点やID順は未規定です。
制約: 0<=id<cycle_count()。
計算量: O(1)。
successorint successor(int v) const;
vの行先を返します。
制約: 0<=v<N。
計算量: O(1)。
successorsstd::span<const int> successors() const noexcept;
全頂点の行先への読み取り専用spanを返します。
制約: なし。
計算量: O(1)。
on_cyclebool on_cycle(int v) const;
vが周期上ならtrueを返します。周期上ではinfo(v).depth=0、entry=vです。
制約: 0<=v<N。
計算量: O(1)。
cycle_countint cycle_count() const noexcept;
周期の個数を返します。空グラフでは0です。
制約: なし。
計算量: O(1)。
component_sizeint component_size(int v) const;
vと同じ弱連結成分全体の頂点数を返します。周期長とは異なります。
制約: 0<=v<N。
計算量: O(1)。
sizeint size() const noexcept;
頂点数を返します。
制約: なし。
計算量: O(1)。
emptybool empty() const noexcept;
0頂点ならtrueを返します。
制約: なし。
計算量: O(1)。
clearvoid clear() noexcept;
空へ戻します。
制約: なし。
計算量: 保持領域の解放に比例します。
swapvoid swap(FunctionalGraph& other) noexcept;
void swap(FunctionalGraph& a, FunctionalGraph& b) noexcept;
状態を交換します。
制約: なし。
計算量: O(1)。
operator=FunctionalGraph& operator=(const FunctionalGraph& other);
FunctionalGraph& operator=(FunctionalGraph&& other) noexcept;
コピー/ムーブ代入し、自身への参照を返します。
制約: なし。
計算量: コピーはO(N log(N+1))、旧状態の破棄費用を加えます。
コピーは元のグラフから独立し、move元は空になります。buildやコピー代入で領域を確保できなかった場合も、以前の状態とviewは有効です。viewは再構築・clear・代入・所有権の移動が成功するまで使えます。
頂点・周期ID・入力の行先を既定で検査し、SKIP_RUNTIME_CHECKSで除きます。容量保護は維持します。
std::vector<int> next{2, 0, 3, 2};
FunctionalGraph graph(next);
int v = graph.kth_successor(1, 1000000000000000000ULL);
auto distance = graph.distance(1, 3); // 3
FunctionalGraph() / FunctionalGraph(span<const int> successor): 空/各頂点の行先で構築。
build(successor): 再構築。頂点0..n-1、各頂点に行先1つ。ラベル順に制約なし。自己辺可。
O(n log(n+1))時間・領域。入力走査中に行先を検査。失敗時は旧状態とviewを維持。
size()/empty(), successor(v), successors(): 頂点数/空判定/行先/const span。O(1)。
kth_successor(v,uint64_t k): k回進んだ頂点。全uint64_t範囲可。O(log(n+1))。
distance(from,to): 初めて到達する辺数。到達不能は-1。O(log(n+1))。
reachable(from,to): distance>=0。O(log(n+1))。
info(v): CycleInfo {id,entry,depth,position,length}。O(1)。entryは最初の周期頂点、
depthは到達辺数、positionはそのentryの周期内添字、lengthは周期長。
on_cycle(v), cycle_count(), component_size(v): 周期上か/周期数/同じ弱連結成分の頂点数。O(1)。
cycle(id): successor方向に並ぶ周期頂点のconst span。O(1)。周期ID/始点は構築時の内部順。
clear(): 空へ。copyは独立所有、copy代入は失敗時旧状態維持。move元は空で再利用可。swapはO(1)。
viewは成功したbuild/clear/代入/所有権移動まで有効。buildの入力に自身のviewを渡してよい。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| E - Permute K times | functional_graph.cpp | 未提出 | — |
✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。
| 検査 | 状態 |
|---|---|
| 正常系 | 未実施 |
| 失敗系 | 未測定 |
| Library Checker公式ケース | 無し |
| 性能測定 | 未実施 |
| ASan/UBSan | 未実施 |
| カバレッジ | 未実施 |
到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。
// SPDX-License-Identifier: CC0-1.0
// 参考: https://nyaannyaan.github.io/library/graph/functional-graph.hpp
// https://atcoder.jp/contests/abc367/tasks/abc367_e
// 入次数除去・周期分解・ダブリングを用いて独立実装。
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/functional_graph.md
// 行先・頂点・周期IDの検査はSKIP_RUNTIME_CHECKSで除外。配列容量の上限保護は維持。
// API一覧
// FunctionalGraph() / FunctionalGraph(span<const int> successor): 空/各頂点の行先で構築。
// build(successor): 再構築。頂点0..n-1、各頂点に行先1つ。ラベル順に制約なし。自己辺可。
// O(n log(n+1))時間・領域。入力走査中に行先を検査。失敗時は旧状態とviewを維持。
// size()/empty(), successor(v), successors(): 頂点数/空判定/行先/const span。O(1)。
// kth_successor(v,uint64_t k): k回進んだ頂点。全uint64_t範囲可。O(log(n+1))。
// distance(from,to): 初めて到達する辺数。到達不能は-1。O(log(n+1))。
// reachable(from,to): distance>=0。O(log(n+1))。
// info(v): CycleInfo {id,entry,depth,position,length}。O(1)。entryは最初の周期頂点、
// depthは到達辺数、positionはそのentryの周期内添字、lengthは周期長。
// on_cycle(v), cycle_count(), component_size(v): 周期上か/周期数/同じ弱連結成分の頂点数。O(1)。
// cycle(id): successor方向に並ぶ周期頂点のconst span。O(1)。周期ID/始点は構築時の内部順。
// clear(): 空へ。copyは独立所有、copy代入は失敗時旧状態維持。move元は空で再利用可。swapはO(1)。
// viewは成功したbuild/clear/代入/所有権移動まで有効。buildの入力に自身のviewを渡してよい。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <span>
#include <stdexcept>
#include <utility>
#include <vector>
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_FUNCTIONAL_GRAPH_DEFINED
#define SIRKIT_FUNCTIONAL_GRAPH_DEFINED
namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ {
inline void CheckFunctionalVertexCount(std::size_t vertices) {
if (vertices > static_cast<std::size_t>(std::numeric_limits<int>::max()))
throw std::length_error("FunctionalGraph size");
}
inline std::size_t FunctionalLiftingCount(std::size_t vertices, unsigned levels) {
if (levels && vertices > std::vector<int>{}.max_size() / levels)
throw std::length_error("FunctionalGraph lifting capacity");
return vertices * levels;
}
}
class FunctionalGraph {
public:
struct CycleInfo { int id, entry, depth, position, length; };
private:
std::vector<int> next_, depth_, entry_, cycle_id_, position_, component_size_, cycle_vertices_, jump_;
std::vector<std::size_t> cycle_offsets_;
unsigned levels_ = 0;
void check_vertex(int v) const {
#ifndef SKIP_RUNTIME_CHECKS
if (v < 0 || static_cast<std::size_t>(v) >= next_.size()) throw std::out_of_range("FunctionalGraph vertex");
#else
(void)v;
#endif
}
void initialize(std::span<const int> successors) {
const auto n = successors.size();
/*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::CheckFunctionalVertexCount(n);
next_.assign(successors.begin(), successors.end());
std::vector<int> indegree(n), order; order.reserve(n);
for (const int v : next_) {
#ifndef SKIP_RUNTIME_CHECKS
if (v < 0 || static_cast<std::size_t>(v) >= n) throw std::out_of_range("FunctionalGraph successor");
#endif
++indegree[v];
}
for (std::size_t v = 0; v < n; ++v) if (!indegree[v]) order.push_back(static_cast<int>(v));
for (std::size_t i = 0; i < order.size(); ++i) if (--indegree[next_[order[i]]] == 0) order.push_back(next_[order[i]]);
depth_.resize(n); entry_.resize(n); position_.resize(n); cycle_id_.assign(n, -1);
cycle_offsets_.push_back(0);
for (std::size_t i = 0; i < n; ++i) if (indegree[i] && cycle_id_[i] == -1) {
const auto id = static_cast<int>(component_size_.size());
int v = static_cast<int>(i), position = 0;
do {
cycle_id_[v] = id; entry_[v] = v; position_[v] = position++;
cycle_vertices_.push_back(v); v = next_[v];
} while (v != static_cast<int>(i));
component_size_.push_back(position); cycle_offsets_.push_back(cycle_vertices_.size());
}
int max_depth = 0;
for (auto i = order.size(); i != 0; --i) {
const int v = order[i - 1], p = next_[v];
depth_[v] = depth_[p] + 1; entry_[v] = entry_[p]; cycle_id_[v] = cycle_id_[p]; position_[v] = position_[p];
++component_size_[cycle_id_[v]]; max_depth = std::max(max_depth, depth_[v]);
}
levels_ = std::bit_width(static_cast<unsigned>(max_depth));
jump_.resize(/*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::FunctionalLiftingCount(n, levels_));
if (levels_) std::copy(next_.begin(), next_.end(), jump_.begin());
for (unsigned level = 1; level < levels_; ++level) {
const auto before = n * (level - 1), here = n * level;
for (std::size_t v = 0; v < n; ++v) jump_[here + v] = jump_[before + static_cast<std::size_t>(jump_[before + v])];
}
}
int jump_tree(int v, std::uint64_t k) const noexcept {
const auto n = next_.size();
for (unsigned level = 0; k; ++level, k >>= 1) if (k & 1) v = jump_[n * level + static_cast<std::size_t>(v)];
return v;
}
public:
FunctionalGraph() = default;
explicit FunctionalGraph(std::span<const int> successors) { initialize(successors); }
FunctionalGraph(const FunctionalGraph&) = default;
FunctionalGraph& operator=(const FunctionalGraph& other) { if (this != &other) { FunctionalGraph copy(other); swap(copy); } return *this; }
FunctionalGraph(FunctionalGraph&& other) noexcept { swap(other); }
FunctionalGraph& operator=(FunctionalGraph&& other) noexcept { if (this != &other) { clear(); swap(other); } return *this; }
void swap(FunctionalGraph& other) noexcept {
next_.swap(other.next_); depth_.swap(other.depth_); entry_.swap(other.entry_); cycle_id_.swap(other.cycle_id_);
position_.swap(other.position_); component_size_.swap(other.component_size_); cycle_vertices_.swap(other.cycle_vertices_);
jump_.swap(other.jump_); cycle_offsets_.swap(other.cycle_offsets_); std::swap(levels_, other.levels_);
}
friend void swap(FunctionalGraph& a, FunctionalGraph& b) noexcept { a.swap(b); }
void build(std::span<const int> successors) { FunctionalGraph next(successors); swap(next); }
int size() const noexcept { return static_cast<int>(next_.size()); }
bool empty() const noexcept { return next_.empty(); }
int successor(int v) const { check_vertex(v); return next_[v]; }
std::span<const int> successors() const noexcept { return next_; }
int cycle_count() const noexcept { return static_cast<int>(component_size_.size()); }
bool on_cycle(int v) const { check_vertex(v); return depth_[v] == 0; }
int component_size(int v) const { check_vertex(v); return component_size_[cycle_id_[v]]; }
std::span<const int> cycle(int id) const {
#ifndef SKIP_RUNTIME_CHECKS
if (id < 0 || id >= cycle_count()) throw std::out_of_range("FunctionalGraph cycle");
#endif
const auto first = cycle_offsets_[id], last = cycle_offsets_[id + 1];
return std::span<const int>(cycle_vertices_).subspan(first, last - first);
}
CycleInfo info(int v) const {
check_vertex(v); const int id = cycle_id_[v];
return {id, entry_[v], depth_[v], position_[v], static_cast<int>(cycle_offsets_[id + 1] - cycle_offsets_[id])};
}
int kth_successor(int v, std::uint64_t k) const {
check_vertex(v);
const auto depth = static_cast<std::uint64_t>(depth_[v]);
if (k < depth) return jump_tree(v, k);
const auto id = cycle_id_[v];
const auto length = cycle_offsets_[id + 1] - cycle_offsets_[id];
const auto offset = (static_cast<std::size_t>((k - depth) % length) + static_cast<std::size_t>(position_[v])) % length;
return cycle_vertices_[cycle_offsets_[id] + offset];
}
std::int64_t distance(int from, int to) const {
check_vertex(from); check_vertex(to);
if (cycle_id_[from] != cycle_id_[to] || depth_[from] < depth_[to]) return -1;
if (depth_[to]) {
const auto d = static_cast<std::uint64_t>(depth_[from] - depth_[to]);
return jump_tree(from, d) == to ? static_cast<std::int64_t>(d) : -1;
}
const auto id = cycle_id_[from];
const auto length = static_cast<std::int64_t>(cycle_offsets_[id + 1] - cycle_offsets_[id]);
const auto offset = (static_cast<std::int64_t>(position_[to]) - position_[from] + length) % length;
return static_cast<std::int64_t>(depth_[from]) + offset;
}
bool reachable(int from, int to) const { return distance(from, to) >= 0; }
void clear() noexcept {
next_.clear(); depth_.clear(); entry_.clear(); cycle_id_.clear(); position_.clear(); component_size_.clear();
cycle_vertices_.clear(); jump_.clear(); cycle_offsets_.clear(); levels_ = 0;
}
};
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1