競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
頂点ごとの値を $A_u$ とし、$A_v=A_u w$ という制約を管理します。$w$ は行列や置換など、掛ける順番で結果が変わる群の要素でも使えます。
op(a,b) は積 $ab$、e() は単位元、inverse(a) は逆元を返します。$S$ はコピー・ムーブ構築と等値比較ができ、ムーブ代入が例外を送出しない型を使います。頂点番号は 0..n-1 です。群の演算と値のコピーを定数時間と数え、$\alpha$ は逆アッカーマン関数とします。頂点を指定する操作は、いずれも1回で最悪 $O(1+\log(n+1))$ です。
NoncommutativeWeightedUnionFindtemplate <std::equality_comparable S, auto op, auto e, auto inverse>
class NoncommutativeWeightedUnionFind;
explicit NoncommutativeWeightedUnionFind(std::size_t n = 0);
互いに独立した頂点を $n$ 個作ります。$n$ は INT_MAX 以下です。 $O(n+1)$ 時間・領域です。
unite_checkedMergeResult unite_checked(int from, int to, const S &relation);
$A_{to}=A_{from}\,\mathrm{relation}$ を課します。戻り値 MergeResult は、新規結合なら Merged、既存の制約と一致するなら AlreadyConsistent、矛盾なら Contradiction です。矛盾時は既存の制約を保ちます。
代表からの差を $g_{from},g_{to}$ とすると、from 側の代表を残す場合は、吸収される代表に $g_{from}\,\mathrm{relation}\,g_{to}^{-1}$ を持たせます。to 側の代表を残す場合は、この積の逆元を使います。 償却 $O(\alpha(n+1))$ です。
constrainbool constrain(int from, int to, const S &relation);
制約を課し、新しく結合したか、既に制約を満たしていれば true を返します。 償却 $O(\alpha(n+1))$ です。
mergebool merge(int from, int to, const S &relation);
制約を課し、新しく結合した場合だけ true を返します。 償却 $O(\alpha(n+1))$ です。
unitevoid unite(int from, int to, const S &relation);
制約を課します。矛盾時は既存の制約を保ちます。 償却 $O(\alpha(n+1))$ です。
diffS diff(int from, int to);
同じ成分の頂点に対して $A_{from}^{-1}A_{to}$ を返します。異なる成分の頂点を渡すと、入力検査が有効な場合は std::invalid_argument を送出します。 償却 $O(\alpha(n+1))$ です。
try_diffstd::optional<S> try_diff(int from, int to);
同じ成分なら $A_{from}^{-1}A_{to}$、異なる成分なら std::nullopt を返します。 償却 $O(\alpha(n+1))$ です。
consistentbool consistent(int from, int to, const S &relation);
制約を追加せず、矛盾するかを確認します。異なる成分か、既存の制約と一致する場合は true を返します。 償却 $O(\alpha(n+1))$ です。
rootint root(int vertex);
頂点の成分の代表を返します。 償却 $O(\alpha(n+1))$ です。
leaderint leader(int vertex);
頂点の成分の代表を返します。root(vertex) と同じです。 償却 $O(\alpha(n+1))$ です。
samebool same(int a, int b);
頂点 a と b が同じ成分に属するかを返します。 償却 $O(\alpha(n+1))$ です。
issamebool issame(int a, int b);
頂点 a と b が同じ成分に属するかを返します。same(a,b) と同じです。 償却 $O(\alpha(n+1))$ です。
weightS weight(int vertex);
成分の代表から頂点への差を返します。 償却 $O(\alpha(n+1))$ です。
root_with_weightstd::pair<int, S> root_with_weight(int vertex);
成分の代表と、その代表から頂点への差を順に返します。 償却 $O(\alpha(n+1))$ です。
sizeint size(int vertex);
int size() const noexcept;
size(vertex) は頂点の成分の頂点数を償却 $O(\alpha(n+1))$ で返します。size() は全頂点数を $O(1)$ で返します。
emptybool empty() const noexcept;
全頂点数が0なら true を返します。 $O(1)$ です。
component_countint component_count() const noexcept;
現在の成分数を返します。 $O(1)$ です。
using UF = sirkit::NoncommutativeWeightedUnionFind<Permutation, compose, identity, inverse>;
UF uf(3);
uf.constrain(0, 1, p);
uf.constrain(2, 1, inverse(q));
const auto forward = uf.diff(0, 2); // p*q
const auto backward = uf.diff(2, 0); // inv(q)*inv(p)
重み付き Union Find は加法による差を扱います。Library Checker の $A_u=A_v x$ は、このAPIで constrain(v,u,x) と書きます。
使用例 / Verify / Library Checker
NoncommutativeWeightedUnionFind<S,op,e,inverse>(n=0): n頂点を独立に構築。O(n+1)時間・領域。
unite_checked(from,to,w): A_to=A_from*wを追加。Merged/AlreadyConsistent/Contradictionを返す。
constrain(from,to,w): 矛盾しない場合true。merge: 新規結合ならtrue。unite: 戻り値なし。
diff(from,to): A_from^{-1}*A_to。try_diffは別成分ならnullopt、consistentは制約を追加せず判定。
root(i)/leader(i), same(a,b)/issame(a,b), size(i): 代表、連結判定、成分サイズ。
weight(i): 代表からiへの差。root_with_weight(i): {代表, weight(i)}。
size()/empty()/component_count(): 全頂点数、空判定、成分数。O(1)。他は償却O(α(n+1))。
op/e/inverseは群の積/単位元/逆元。Sはコピー可能でムーブ代入が非送出、等値比較可能。
頂点は0..n-1、n<=INT_MAX。演算・コピーの計算時間をO(1)としたときの計算量。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| Unionfind with Potential (Non-Commutative Group) | unionfind_with_potential_non_commutative_group.cpp | ✓ 現行AC | AC |
✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。
| 検査 | 状態 |
|---|---|
| 正常系 | 未実施 |
| 失敗系 | 未測定 |
| Library Checker公式ケース | 未測定 |
| 性能測定 | 未実施 |
| ASan/UBSan | 未実施 |
| カバレッジ | 未実施 |
到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。
// SPDX-License-Identifier: CC0-1.0
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/noncommutative_weighted_union_find.md
//
// API一覧
// NoncommutativeWeightedUnionFind<S,op,e,inverse>(n=0): n頂点を独立に構築。O(n+1)時間・領域。
// unite_checked(from,to,w): A_to=A_from*wを追加。Merged/AlreadyConsistent/Contradictionを返す。
// constrain(from,to,w): 矛盾しない場合true。merge: 新規結合ならtrue。unite: 戻り値なし。
// diff(from,to): A_from^{-1}*A_to。try_diffは別成分ならnullopt、consistentは制約を追加せず判定。
// root(i)/leader(i), same(a,b)/issame(a,b), size(i): 代表、連結判定、成分サイズ。
// weight(i): 代表からiへの差。root_with_weight(i): {代表, weight(i)}。
// size()/empty()/component_count(): 全頂点数、空判定、成分数。O(1)。他は償却O(α(n+1))。
// op/e/inverseは群の積/単位元/逆元。Sはコピー可能でムーブ代入が非送出、等値比較可能。
// 頂点は0..n-1、n<=INT_MAX。演算・コピーの計算時間をO(1)としたときの計算量。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <concepts>
#include <cstddef>
#include <functional>
#include <limits>
#include <optional>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_NONCOMMUTATIVE_WEIGHTED_UNION_FIND_DEFINED
#define SIRKIT_NONCOMMUTATIVE_WEIGHTED_UNION_FIND_DEFINED
template <std::equality_comparable S, auto op, auto e, auto inverse>
class NoncommutativeWeightedUnionFind
{
static_assert(std::is_invocable_r_v<S, decltype(op), const S &, const S &>);
static_assert(std::is_invocable_r_v<S, decltype(e)>);
static_assert(std::is_invocable_r_v<S, decltype(inverse), const S &>);
static_assert(std::is_copy_constructible_v<S> && std::is_move_constructible_v<S> &&
std::is_nothrow_move_assignable_v<S>);
public:
enum class MergeResult
{
Merged,
AlreadyConsistent,
Contradiction,
};
explicit NoncommutativeWeightedUnionFind(std::size_t n = 0)
: parent_(CheckedSize(n), -1), potential_(n, std::invoke(e)), components_(static_cast<int>(n))
{
}
NoncommutativeWeightedUnionFind(const NoncommutativeWeightedUnionFind &) = default;
NoncommutativeWeightedUnionFind &operator=(const NoncommutativeWeightedUnionFind &other)
{
if (this != &other)
{
NoncommutativeWeightedUnionFind replacement(other);
Swap(replacement);
}
return *this;
}
NoncommutativeWeightedUnionFind(NoncommutativeWeightedUnionFind &&other) noexcept
: parent_(std::move(other.parent_)), potential_(std::move(other.potential_)),
components_(std::exchange(other.components_, 0))
{
other.parent_.clear();
other.potential_.clear();
}
NoncommutativeWeightedUnionFind &operator=(NoncommutativeWeightedUnionFind &&other) noexcept
{
if (this != &other)
{
NoncommutativeWeightedUnionFind replacement(std::move(other));
Swap(replacement);
}
return *this;
}
[[nodiscard]] int size() const noexcept
{
return static_cast<int>(parent_.size());
}
[[nodiscard]] bool empty() const noexcept
{
return parent_.empty();
}
[[nodiscard]] int component_count() const noexcept
{
return components_;
}
[[nodiscard]] int root(int vertex)
{
CheckVertex(vertex);
return Compress(vertex);
}
[[nodiscard]] int leader(int vertex)
{
return root(vertex);
}
[[nodiscard]] bool same(int a, int b)
{
CheckVertex(a);
CheckVertex(b);
const auto representative = Compress(a);
return representative == Compress(b);
}
[[nodiscard]] bool issame(int a, int b)
{
return same(a, b);
}
[[nodiscard]] int size(int vertex)
{
return -parent_[root(vertex)];
}
[[nodiscard]] S weight(int vertex)
{
CheckVertex(vertex);
Compress(vertex);
return potential_[vertex];
}
[[nodiscard]] std::pair<int, S> root_with_weight(int vertex)
{
const auto representative = root(vertex);
return {representative, potential_[vertex]};
}
[[nodiscard]] std::optional<S> try_diff(int from, int to)
{
if (!same(from, to))
{
return std::nullopt;
}
return Product(Inverse(potential_[from]), potential_[to]);
}
[[nodiscard]] S diff(int from, int to)
{
auto result = try_diff(from, to);
#ifndef SKIP_RUNTIME_CHECKS
if (!result)
{
throw std::invalid_argument("NoncommutativeWeightedUnionFind: disjoint vertices");
}
#endif
return std::move(*result);
}
[[nodiscard]] bool consistent(int from, int to, const S &relation)
{
return !same(from, to) || Product(potential_[from], relation) == potential_[to];
}
MergeResult unite_checked(int from, int to, const S &relation)
{
CheckVertex(from);
CheckVertex(to);
auto keep = Compress(from);
auto absorbed = Compress(to);
const auto proposed = Product(potential_[from], relation);
if (keep == absorbed)
{
return proposed == potential_[to] ? MergeResult::AlreadyConsistent : MergeResult::Contradiction;
}
// A_to=A_from*relation。根保持側から吸収側への差はg_from*relation*inv(g_to)。
auto bridge = Product(proposed, Inverse(potential_[to]));
if (parent_[keep] > parent_[absorbed])
{
bridge = Inverse(bridge);
std::swap(keep, absorbed);
}
potential_[absorbed] = std::move(bridge);
parent_[keep] += parent_[absorbed];
parent_[absorbed] = keep;
--components_;
return MergeResult::Merged;
}
bool constrain(int from, int to, const S &relation)
{
return unite_checked(from, to, relation) != MergeResult::Contradiction;
}
bool merge(int from, int to, const S &relation)
{
return unite_checked(from, to, relation) == MergeResult::Merged;
}
void unite(int from, int to, const S &relation)
{
(void)unite_checked(from, to, relation);
}
private:
std::vector<int> parent_;
// potential_[v] は親からvへの差。根の値は単位元。
std::vector<S> potential_;
int components_;
static std::size_t CheckedSize(std::size_t n)
{
if (n > static_cast<std::size_t>(std::numeric_limits<int>::max()))
{
throw std::length_error("NoncommutativeWeightedUnionFind: too many vertices");
}
return n;
}
void Swap(NoncommutativeWeightedUnionFind &other) noexcept
{
parent_.swap(other.parent_);
potential_.swap(other.potential_);
std::swap(components_, other.components_);
}
void CheckVertex(int vertex) const
{
#ifndef SKIP_RUNTIME_CHECKS
if (static_cast<std::size_t>(vertex) >= parent_.size())
{
throw std::out_of_range("NoncommutativeWeightedUnionFind: invalid vertex");
}
#else
(void)vertex;
#endif
}
static S Product(const S &a, const S &b)
{
return std::invoke(op, a, b);
}
static S Inverse(const S &value)
{
return std::invoke(inverse, value);
}
int Compress(int vertex)
{
const int parent = parent_[vertex];
if (parent < 0)
{
return vertex;
}
if (parent_[parent] < 0)
{
return parent;
}
const int representative = Compress(parent);
auto combined = Product(potential_[parent], potential_[vertex]);
potential_[vertex] = std::move(combined);
parent_[vertex] = representative;
return representative;
}
};
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1