sirkit-cpp-library

競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。

View the Project on GitHub reinsirk/sirkit-cpp-library

完全永続Union Find

DataStructure/persistent-union-find.cpp · ソース · 文書 Last Commit

通常版・コンパイラ共通 · この版の一覧へ

通常版・GCC専用 · この版の一覧へ

通常版・Clang専用 · この版の一覧へ

通常版・MSVC専用 · この版の一覧へ

速度優先版・コンパイラ共通 · この版の一覧へ

速度優先版・GCC専用 · この版の一覧へ

速度優先版・Clang専用 · この版の一覧へ

速度優先版・MSVC専用 · この版の一覧へ

過去の版を保持します。保存したどの版からでも、結合を行って新しい版を作れます。 永続配列と成分サイズによる結合を使い、経路圧縮は行いません。代表の取得・連結判定はO(log²(n+1))、結合は償却O(log²(n+1))です。 全操作を先読みできる問題では、版の分岐を木で表し、rollback UFで処理する方が速い場合があります。このライブラリでは先読みせずに保存版を照会・更新できます。

Union FindのAPI

VersionはPersistentUnionFind::Versionを指し、実体は非所有のNode*です(Node = PersistentArray<int>::Node)。代表頂点番号のintとは区別します。頂点は0<=i<n、指定版は同じ保存領域の有効なハンドルを渡します。

PersistentUnionFind

explicit PersistentUnionFind(std::size_t n = 0);

n頂点を独立した成分として構築します。

制約: n<=INT_MAX。

計算量: B=16としてO(B+log_B(n+1))時間。

find

int find(int i) const;
int find(int i, Version version) const;

現在版/指定版で代表頂点を返します。

制約: 指定する頂点は0以上n未満、版は同じ保存領域の有効なハンドル。

計算量: O(log²(n+1))。

leader

int leader(int i) const;
int leader(int i, Version version) const;

現在版/指定版で代表頂点を返します。

制約: 指定する頂点は0以上n未満、版は同じ保存領域の有効なハンドル。

計算量: O(log²(n+1))。

root

int root(int i) const;
int root(int i, Version version) const;

現在版/指定版で代表頂点を返します。

制約: 指定する頂点は0以上n未満、版は同じ保存領域の有効なハンドル。

計算量: O(log²(n+1))。

find_with_size

std::pair<int,int> find_with_size(int i) const;
std::pair<int,int> find_with_size(int i, Version version) const;

現在版/指定版で{代表頂点, 負の成分サイズ}を返します。

制約: 指定する頂点は0以上n未満、版は同じ保存領域の有効なハンドル。

計算量: O(log²(n+1))。

size

int size(int i) const;
int size(int i, Version version) const;
int size() const noexcept;

現在版/指定版で頂点iの成分サイズ。引数なしは全頂点数を返します。

制約: 指定する頂点は0以上n未満、版は同じ保存領域の有効なハンドル。

計算量: O(log²(n+1))。引数なしはO(1)。

same

bool same(int i, int j) const;
bool same(int i, int j, Version version) const;

現在版/指定版で同じ成分かを返します。

制約: 指定する頂点は0以上n未満、版は同じ保存領域の有効なハンドル。

計算量: O(log²(n+1))。

issame

bool issame(int i, int j) const;
bool issame(int i, int j, Version version) const;

sameの別名です。同じ引数で現在版/指定版を照会し、戻り値・前提も同じです。計算量はO(log²(n+1))です。

unite

bool unite(int i, int j);
bool unite(int i, int j, Version version);

現在版または指定版から分岐して結合し、結果を現在版にします。新たに結合したときだけtrueを返します。結果の版のハンドルはversion()で取得します。

制約: 頂点は範囲内、版は同じ保存領域の有効なハンドル。

計算量: 償却O(log²(n+1))時間、成功時O(log(n+1))ノードを追加。

merge

bool merge(int i, int j);
bool merge(int i, int j, Version version);

現在版/指定版から分岐して結合し、結果を現在版にします。新規結合したときだけtrueです。

制約: 頂点は範囲内、版は同じ保存領域の有効なハンドル。

計算量: 償却O(log²(n+1))時間、成功時O(log(n+1))ノードを追加。

version

Version version() const noexcept;

現在版の非所有ハンドルを返します。

制約: 保持する間は同じ保存領域の所有者を存続させます。

計算量: O(1)。

restore

void restore(Version version);

現在版を選択します。

制約: 同じ保存領域の有効な版。非空UFではnullを指定できません。

計算量: O(1)。

component_count

int component_count() const;
int component_count(Version version) const;

現在版/指定版の成分数を返します。

制約: 同じ保存領域の有効な版。

計算量: O(n log(n+1))。

groups

std::vector<std::vector<int>> groups() const;
std::vector<std::vector<int>> groups(Version version) const;

現在版/指定版の成分一覧を返します。各成分内の頂点は昇順です。

制約: 同じ保存領域の有効な版。

計算量: O(n log²(n+1))時間・O(n+1)返却領域。

[,version]は版を末尾に指定するオーバーロードです。頂点は0<=i<n。結合不要でも、指定版が現在版になります。

using UF = PersistentUnionFind;
UF uf(4);
auto initial = uf.version();
uf.unite(0, 1);
UF::Version left = uf.version();
std::vector<UF::Version> versions{initial, left};
uf.unite(2, 3, versions[0]);
assert(!uf.same(0, 1) && uf.issame(0, 1, versions[1]));

nは頂点数です。find・leader・root・find_with_size・size(i)・same・issameはO(log²(n+1))、結合は償却O(log²(n+1))時間で、成功時O(log(n+1))ノードを追加します。構築は後述の定数配列と同じ費用です。版の取得・選択・引数なしsizeはO(1)、component_countはO(n log(n+1))、groupsはO(n log²(n+1))時間です。

永続配列のAPI

PersistentArray<T,shift=4>も単独で使えます。B=2^shift、1<=shift<=8、添字はint64_t、0<=n<=INT64_MAX。Tはコピー構築・代入に対応し、初期値省略時はT{}を構築できることが必要です。

PersistentArray

explicit PersistentArray(std::int64_t n = 0, T ID = T{});
explicit PersistentArray(const std::vector<T>& values, T ID = T{});

全要素がIDの疎な配列を作るか、vectorから構築します。

制約: 0<=n<=INT64_MAX、1<=shift<=8。Tのコピー・代入が必要です。

計算量: 定数配列はO(B+log_B(n+1))時間。vector版はO(B+n+(n/B+1)log_B(n+1))時間・O(n+B)領域。

get

T get(std::int64_t k) const;
T get(Node* version, std::int64_t k) const;

現在版/指定版の値をコピーして返します。

制約: 0<=k<size()。同じ保存領域の有効な版、nullは全要素IDの版。

計算量: O(log_B(n+1))。

get_two

std::pair<T,T> get_two(std::int64_t a, std::int64_t b) const;
std::pair<T,T> get_two(Node* version, std::int64_t a, std::int64_t b) const;

2要素を指定した順に返します。同じ添字も使えます。

制約: 添字は範囲内、版はgetと同じ条件。

計算量: O(log_B(n+1))。

update

Node* update(std::int64_t k, const T& value);
Node* update(Node* version, std::int64_t k, const T& value);

1点を変更した新しい版を現在版にし、そのハンドルを返します。

制約: 添字は範囲内、版はgetと同じ条件。

計算量: 償却O(B log_B(n+1))時間・追加領域。

update_two

Node* update_two(std::int64_t a, const T& x, std::int64_t b, const T& y);
Node* update_two(Node* version, std::int64_t a, const T& x, std::int64_t b, const T& y);

2点を同時更新した版を現在版にし、ハンドルを返します。同じ添字ならyを優先します。

制約: 添字は範囲内、版はgetと同じ条件。

計算量: 償却O(B log_B(n+1))時間・追加領域。

restore(PersistentArray)

void restore(Node* version);

現在版を選択します。

制約: 同じ保存領域の有効なハンドル。nullは全要素IDの版。

計算量: O(1)。

root(公開データ)

Node* root;

現在版の非所有ハンドルです。

制約: 同じ保存領域の所有者が残る間だけ有効です。

計算量: 読取りO(1)。

size(PersistentArray)

std::int64_t size() const noexcept;

配列の要素数を返します。

制約: 追加の制約はありません。

計算量: O(1)。

配列のnullptr版は全要素がIDの版です。Union Findの非空インスタンスでは、公開APIから得た非null版を渡します。

get・get_twoはO(log_B(n+1))、更新は償却O(B log_B(n+1))時間・追加領域です。定数配列の構築はO(B+log_B(n+1))時間、vectorからはO(B+n+(n/B+1)log_B(n+1))時間・O(n+B)領域です。

版の寿命・失敗

コピーは保存領域を共有し、現在版を個別に保持します。一方の更新は他方の現在版・過去版を変えません。ムーブ元は空です。

版ハンドルは同じ保存領域を所有するインスタンス(UFでは元のUFまたはそのコピー)が残る間だけ有効です。ハンドルに所有権はありません。deleteや直接の参照外しは行いません。別の保存領域のハンドルや寿命が切れたハンドルは渡せません。並行更新には外部同期が必要です。最後の所有者が破棄されると全版を解放します。

更新失敗でも現在版・保存版を保ちますが、作成途中のノードや確保済み容量は残る場合があります。公開arrの直接変更はUnion Findの不変条件を壊すため、通常操作には使いません。

既定では添字・版の所有元を検査し、非空Union Findのnull版はinvalid_argument、範囲外はout_of_rangeです。寿命切れ検出の保証はありません。SKIP_RUNTIME_CHECKSで入力検査を省いても、サイズ・ノード容量の保護は維持します。

完全な使用例

ソースのAPI注記
[PersistentUnionFind]
PersistentUnionFind(n=0): n要素の完全永続UF。初期化O(log(n+1))、初期ノード数O(1)。頂点はintの範囲。
root(i[,version])/leader(i[,version])/find(i[,version]): intの代表頂点、size(i[,version]): 成分サイズ。O(log²(n+1))。
find_with_size(i[,version]): {代表,負の成分サイズ}。same(a,b[,version])/issame(a,b[,version]): 同一成分か。O(log²(n+1))。
unite(a,b[,version])/merge(a,b[,version]): 指定版/現在版から結合し新規結合ならtrue。O(log²(n+1))償却時間。
結合不要でも指定版が現在版になる。成功1回でO(log(n+1))ノードを追加し全版を保持する。
Versionは非所有Node*の版ハンドルで、頂点番号ではない。version()で取得して保存し、参照・deleteはしない。
version(): 現在版のVersion、restore(version): 現在版を選択、size(): 全要素数。O(1)。
component_count([version]): 成分数、O(n log(n+1))。groups([version]): 成分別頂点昇順一覧、O(n log²(n+1))。
コピーは保存領域を共有し現在版は独立、移動元は空。ハンドルの寿命はPersistentArrayと同じ。
arrは互換用公開フィールド。直接更新するとUFの不変条件が壊れるため、操作は上記APIを使う。

[PersistentArray<T,shift>]
PersistentArray<T,shift=4>(n=0,ID=T{}): [0,n)の初期値ID、O(2^shift + log_(2^shift)(n+1))時間。Tはコピー構築・代入可能。
PersistentArray(vector,ID): 配列から構築。B=2^shiftとしてO(B+n+(n/B+1)log_B(n+1))時間、O(n+B)領域。
get(k)/get(version,k): 現在/指定版の値を返す。O(log_(2^shift)(n+1))。
get_two(a,b)/get_two(version,a,b): 2要素をpair<T,T>で返す。2経路を並行参照、同じ計算量。
update(k,val)/update(version,k,val): 現在/指定版から分岐して現在版を更新しNode*を返す。
update_two(a,x,b,y)/update_two(version,a,x,b,y): 2点を同時更新。同じ添字はyを優先しNode*を返す。
update/update_twoはO(2^shift log_(2^shift)(n+1))償却時間・償却追加領域。size(): 要素数、O(1)。
restore(version): 現在版を選択。nullptrは全要素IDの版。O(1)。
rootは現在版の非所有ハンドル。nullptrを指定した版は全要素ID。コピー同士は保存領域を共有し現在版は独立。
ハンドルは同じ保存領域を所有するインスタンスが残る間有効。移動元は空。全版は最後の所有者と同時に反復解放。
別保存領域・寿命切れのハンドルは使用不可。並行更新は外部同期が必要。1<=shift<=8。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Persistent Unionfind persistent_union_find.cpp 現行未照合・要再提出 AC
Union Path Query (Medium)(版別連結・成分距離和) persistent_union_find_union_path_query.cpp 現行未照合・要再提出 AC

✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。

ローカル・CI検査

検査 状態
正常系 未実施
失敗系 未測定
Library Checker公式ケース 未測定
性能測定 未実施
ASan/UBSan 未実施
カバレッジ 未実施

到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。

実行条件・件数・測定結果 · 結果JSON

Verified with

Code

// SPDX-License-Identifier: CC0-1.0
// Original Source: https://nyaannyaan.github.io/library/data-structure/persistent-union-find.hpp.html
// 参考: https://nyaannyaan.github.io/library/data-structure/persistent-array.hpp.html
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/persistent_union_find.md
//
// API一覧
// [PersistentUnionFind]
// PersistentUnionFind(n=0): n要素の完全永続UF。初期化O(log(n+1))、初期ノード数O(1)。頂点はintの範囲。
// root(i[,version])/leader(i[,version])/find(i[,version]): intの代表頂点、size(i[,version]): 成分サイズ。O(log²(n+1))。
// find_with_size(i[,version]): {代表,負の成分サイズ}。same(a,b[,version])/issame(a,b[,version]): 同一成分か。O(log²(n+1))。
// unite(a,b[,version])/merge(a,b[,version]): 指定版/現在版から結合し新規結合ならtrue。O(log²(n+1))償却時間。
// 結合不要でも指定版が現在版になる。成功1回でO(log(n+1))ノードを追加し全版を保持する。
// Versionは非所有Node*の版ハンドルで、頂点番号ではない。version()で取得して保存し、参照・deleteはしない。
// version(): 現在版のVersion、restore(version): 現在版を選択、size(): 全要素数。O(1)。
// component_count([version]): 成分数、O(n log(n+1))。groups([version]): 成分別頂点昇順一覧、O(n log²(n+1))。
// コピーは保存領域を共有し現在版は独立、移動元は空。ハンドルの寿命はPersistentArrayと同じ。
// arrは互換用公開フィールド。直接更新するとUFの不変条件が壊れるため、操作は上記APIを使う。
//
// [PersistentArray<T,shift>]
// PersistentArray<T,shift=4>(n=0,ID=T{}): [0,n)の初期値ID、O(2^shift + log_(2^shift)(n+1))時間。Tはコピー構築・代入可能。
// PersistentArray(vector,ID): 配列から構築。B=2^shiftとしてO(B+n+(n/B+1)log_B(n+1))時間、O(n+B)領域。
// get(k)/get(version,k): 現在/指定版の値を返す。O(log_(2^shift)(n+1))。
// get_two(a,b)/get_two(version,a,b): 2要素をpair<T,T>で返す。2経路を並行参照、同じ計算量。
// update(k,val)/update(version,k,val): 現在/指定版から分岐して現在版を更新しNode*を返す。
// update_two(a,x,b,y)/update_two(version,a,x,b,y): 2点を同時更新。同じ添字はyを優先しNode*を返す。
// update/update_twoはO(2^shift log_(2^shift)(n+1))償却時間・償却追加領域。size(): 要素数、O(1)。
// restore(version): 現在版を選択。nullptrは全要素IDの版。O(1)。
// rootは現在版の非所有ハンドル。nullptrを指定した版は全要素ID。コピー同士は保存領域を共有し現在版は独立。
// ハンドルは同じ保存領域を所有するインスタンスが残る間有効。移動元は空。全版は最後の所有者と同時に反復解放。
// 別保存領域・寿命切れのハンドルは使用不可。並行更新は外部同期が必要。1<=shift<=8。


// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <memory>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_PERSISTENT_ARRAY_DEFINED
#define SIRKIT_PERSISTENT_ARRAY_DEFINED
namespace detail {
inline void CheckPersistentArrayNodeCount(std::size_t size) {
    if (size == std::numeric_limits<std::size_t>::max())
        throw std::length_error("PersistentArray: node capacity");
}

inline std::int64_t CheckedPersistentArraySize(std::size_t size) {
    if (size > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()))
        throw std::length_error("PersistentArray: size overflow");
    return static_cast<std::int64_t>(size);
}
}

template<typename T, int shift = 4>
class PersistentArray {
    friend struct PersistentUnionFind;
    static_assert(shift >= 1 && shift <= 8);
    static constexpr std::size_t width = std::size_t{1} << shift;
#if defined(__GNUC__) && !defined(__clang__)
    static constexpr bool compact_nodes = std::is_trivially_copyable_v<T>;
#else
    static constexpr bool compact_nodes = false;
#endif
    struct Storage;
public:
    struct Node {
    private:
        friend class PersistentArray;
        union TrivialContent {
            std::array<Node*, width> children;
            std::array<T, width> values;
            TrivialContent(std::in_place_index_t<0>, std::array<Node*, width> a) : children(a) {}
            TrivialContent(std::in_place_index_t<1>, std::array<T, width> a) : values(a) {}
        };
        using Content = std::conditional_t<compact_nodes, TrivialContent,
                                          std::variant<std::array<Node*, width>, std::array<T, width>>>;
        Content content;
        auto& children() {
            if constexpr (compact_nodes) return content.children;
            else return std::get<0>(content);
        }
        auto& values() {
            if constexpr (compact_nodes) return content.values;
            else return std::get<1>(content);
        }
#ifndef SKIP_RUNTIME_CHECKS
        const Storage* owner;
#endif
        static std::array<T, width> filled(const T& value) {
            return [&value]<std::size_t... I>(std::index_sequence<I...>) {
                return std::array<T, width>{((void)I, value)...};
            }(std::make_index_sequence<width>{});
        }
    public:
        Node(bool leaf, const T& value, const Storage* storage)
            : content(leaf ? decltype(content)(std::in_place_index<1>, filled(value))
                           : decltype(content)(std::in_place_index<0>, std::array<Node*, width>{}))
#ifndef SKIP_RUNTIME_CHECKS
              , owner(storage)
#endif
        { (void)storage; }
        Node(const Node&) = default;
    };
private:
    // 内側vectorの容量内にだけ追加し、全版のNode*を安定させる。
    struct Storage {
        T id;
        std::vector<std::vector<Node>> blocks;
        std::size_t node_count = 0;
        explicit Storage(T value) : id(std::move_if_noexcept(value)) {}
    };
    std::shared_ptr<Storage> storage_;
    std::int64_t size_ = 0;
    int levels_ = 0;
    void check_index(std::int64_t k) const {
#ifndef SKIP_RUNTIME_CHECKS
        if (k < 0 || k >= size_) throw std::out_of_range("PersistentArray: index");
#else
        (void)k;
#endif
    }
    void check_root(Node* n) const {
#ifndef SKIP_RUNTIME_CHECKS
        if (n && n->owner != storage_.get()) throw std::invalid_argument("PersistentArray: foreign version");
#else
        (void)n;
#endif
    }
    Node* allocate(Node* original, bool leaf) {
        detail::CheckPersistentArrayNodeCount(storage_->node_count);
        if (storage_->blocks.empty() || storage_->blocks.back().size() == storage_->blocks.back().capacity()) {
            std::vector<Node> block;
            block.reserve(std::min<std::size_t>(512, std::size_t{4} << std::min<std::size_t>(storage_->blocks.size(), 9)));
            storage_->blocks.push_back(std::move(block));
        }
        auto& block = storage_->blocks.back();
        if (original) block.emplace_back(*original);
        else block.emplace_back(leaf, storage_->id, storage_.get());
        ++storage_->node_count;
        return &block.back();
    }
public:
    Node* root = nullptr;
    explicit PersistentArray(std::int64_t n = 0, T id = T{}) {
        if (n < 0) throw std::length_error("PersistentArray: negative size");
        size_ = n;
        std::uint64_t top = n ? static_cast<std::uint64_t>(n - 1) : 0;
        while (top >= width) { ++levels_; top >>= shift; }
        storage_ = std::make_shared<Storage>(std::move_if_noexcept(id)); root = allocate(nullptr, levels_ == 0);
    }
    explicit PersistentArray(const std::vector<T>& values, T id = T{})
        : PersistentArray(vector_size(values), std::move_if_noexcept(id)) {
        // 同じ葉の値は続けて代入し、根から葉までの再走査を減らす。
        for (std::size_t first = 0; first < values.size();) {
            Node* node = root;
            for (int d = levels_; d > 0; --d) {
                auto& next = node->children()[(first >> (d * shift)) & (width - 1)];
                if (!next) next = allocate(nullptr, d == 1);
                node = next;
            }
            const auto count = std::min(width, values.size() - first);
            auto& leaf = node->values();
            for (std::size_t j = 0; j < count; ++j) leaf[j] = values[first + j];
            first += count;
        }
    }
    PersistentArray(const PersistentArray&) = default;
    PersistentArray& operator=(const PersistentArray&) = default;
    PersistentArray(PersistentArray&& other) noexcept
        : storage_(std::move(other.storage_)), size_(std::exchange(other.size_, 0)),
          levels_(std::exchange(other.levels_, 0)), root(std::exchange(other.root, nullptr)) {}
    PersistentArray& operator=(PersistentArray&& other) noexcept {
        if (this != &other) {
            storage_ = std::move(other.storage_); size_ = std::exchange(other.size_, 0);
            levels_ = std::exchange(other.levels_, 0); root = std::exchange(other.root, nullptr);
        }
        return *this;
    }
    void restore(Node* r) { check_root(r); root = r; }
    std::int64_t size() const noexcept { return size_; }
    T get(Node* n, std::int64_t k) const {
        check_index(k); check_root(n); return get_unchecked(n, k);
    }
    T get(std::int64_t k) const { return get(root, k); }
    std::pair<T,T> get_two(Node* base, std::int64_t a, std::int64_t b) const {
        check_index(a); check_index(b); check_root(base);
        return get_two_unchecked(base, a, b);
    }
    std::pair<T,T> get_two(std::int64_t a, std::int64_t b) const { return get_two(root, a, b); }
    Node* update(Node* base, std::int64_t k, const T& value) {
        check_index(k); check_root(base);
        std::array<Node*, 64> path;
        std::array<std::size_t, 64> slots;
        const auto index = static_cast<std::uint64_t>(k);
        Node* n = base;
        for (int d = levels_; d > 0; --d) {
            const auto slot = (index >> (d * shift)) & (width - 1);
            path[d] = n; slots[d] = slot;
            n = n ? n->children()[slot] : nullptr;
        }
        Node* result = allocate(n, true);
        result->values()[index & (width - 1)] = value;
        for (int d = 1; d <= levels_; ++d) {
            Node* parent = allocate(path[d], false);
            parent->children()[slots[d]] = result; result = parent;
        }
        return root = result;
    }
    Node* update(std::int64_t k, const T& value) { return update(root, k, value); }
    Node* update_two(Node* base, std::int64_t a, const T& x, std::int64_t b, const T& y) {
        check_index(a); check_index(b); check_root(base);
        return root = update_two(base, static_cast<std::uint64_t>(a), x,
                                 static_cast<std::uint64_t>(b), y, levels_);
    }
    Node* update_two(std::int64_t a, const T& x, std::int64_t b, const T& y) {
        return update_two(root, a, x, b, y);
    }
private:
    Node* update_one(Node* base, std::uint64_t index, const T& value, int level) {
        Node* result = allocate(base, level == 0);
        Node* current = result;
        for (int d = level; d > 0; --d) {
            auto& child = current->children()[(index >> (d * shift)) & (width - 1)];
            child = allocate(child, d == 1);
            current = child;
        }
        current->values()[index & (width - 1)] = value;
        return result;
    }
    // 共通経路は一度だけ複製する。変更は全て新規ノード内で、rootは呼出元が最後に公開。
    Node* update_two(Node* base, std::uint64_t a, const T& x, std::uint64_t b, const T& y, int level) {
        Node* result = allocate(base, level == 0);
        Node* current = result;
        for (int d = level; d > 0; --d) {
            const auto sa = (a >> (d * shift)) & (width - 1);
            const auto sb = (b >> (d * shift)) & (width - 1);
            auto& children = current->children();
            if (sa != sb) {
                children[sa] = update_one(children[sa], a, x, d - 1);
                children[sb] = update_one(children[sb], b, y, d - 1);
                return result;
            }
            children[sa] = allocate(children[sa], d == 1);
            current = children[sa];
        }
        auto& values = current->values();
        values[a & (width - 1)] = x;
        values[b & (width - 1)] = y;
        return result;
    }
    T get_existing(Node* n, std::int64_t k) const {
        const auto index = static_cast<std::uint64_t>(k);
        for (int d = levels_; d > 0; --d)
            n = n->children()[(index >> (d * shift)) & (width - 1)];
        return n->values()[index & (width - 1)];
    }
    T get_unchecked(Node* n, std::int64_t k) const {
        const auto index = static_cast<std::uint64_t>(k);
        for (int d = levels_; d > 0; --d) {
            if (!n) return storage_->id;
            n = n->children()[(index >> (d * shift)) & (width - 1)];
        }
        return n ? n->values()[index & (width - 1)] : storage_->id;
    }
    // 独立な2本の参照を同じ反復で進める。
    std::pair<T,T> get_two_unchecked(Node* n, std::int64_t a, std::int64_t b) const {
        Node* left = n;
        Node* right = n;
        const auto ia = static_cast<std::uint64_t>(a);
        const auto ib = static_cast<std::uint64_t>(b);
        for (int d = levels_; d > 0; --d) {
            if (left) left = left->children()[(ia >> (d * shift)) & (width - 1)];
            if (right) right = right->children()[(ib >> (d * shift)) & (width - 1)];
        }
        return {left ? left->values()[ia & (width - 1)] : storage_->id,
                right ? right->values()[ib & (width - 1)] : storage_->id};
    }
    // UFの親番号は同じ版で明示更新済みなので、祖先の配列経路は必ず存在する。
    std::pair<T,T> get_two_existing(Node* n, std::int64_t a, std::int64_t b) const {
        Node* left = n; Node* right = n;
        const auto ia = static_cast<std::uint64_t>(a), ib = static_cast<std::uint64_t>(b);
        for (int d = levels_; d > 0; --d) {
            left = left->children()[(ia >> (d * shift)) & (width - 1)];
            right = right->children()[(ib >> (d * shift)) & (width - 1)];
        }
        return {left->values()[ia & (width - 1)], right->values()[ib & (width - 1)]};
    }
    static std::int64_t vector_size(const std::vector<T>& values) {
        return detail::CheckedPersistentArraySize(values.size());
    }
};
#endif

#ifndef SIRKIT_PERSISTENT_UNION_FIND_DEFINED
#define SIRKIT_PERSISTENT_UNION_FIND_DEFINED
struct PersistentUnionFind {
    using Node = PersistentArray<int>::Node;
    using Version = Node*;
    PersistentArray<int> arr;
private:
    Version version_ = nullptr;
public:
    explicit PersistentUnionFind(std::size_t n = 0) : arr(checked_size(n), -1), version_(arr.root) {}
    PersistentUnionFind(const PersistentUnionFind&) = default;
    PersistentUnionFind& operator=(const PersistentUnionFind&) = default;
    PersistentUnionFind(PersistentUnionFind&& other) noexcept
        : arr(std::move(other.arr)), version_(std::exchange(other.version_, nullptr)) {}
    PersistentUnionFind& operator=(PersistentUnionFind&& other) noexcept {
        if (this != &other) { arr = std::move(other.arr); version_ = std::exchange(other.version_, nullptr); }
        return *this;
    }
    int size() const noexcept { return static_cast<int>(arr.size()); }
    std::pair<int,int> find_with_size(int i, Version r) const {
        check_version(r); arr.check_index(i);
        int value = arr.get_unchecked(r, i);
        while (value >= 0) { i = value; value = arr.get_existing(r, i); }
        return {i, value};
    }
    std::pair<int,int> find_with_size(int i) const { return find_with_size(i, version_); }
    int find(int i, Version r) const { return find_with_size(i, r).first; }
    int find(int i) const { return find(i, version_); }
    int leader(int i, Version r) const { return find(i, r); }
    int leader(int i) const { return find(i); }
    int root(int i, Version r) const { return find(i, r); }
    int root(int i) const { return find(i); }
    int size(int i, Version r) const { return -find_with_size(i, r).second; }
    int size(int i) const { return size(i, version_); }
    bool same(int i, int j, Version r) const {
        check_version(r); arr.check_index(i); arr.check_index(j);
        if (i == j) return true;
        auto [a, b] = arr.get_two_unchecked(r, i, j);
        // 代表まで上らず、同じ頂点へ到達した時点で連結と分かる。
        while (a >= 0 && b >= 0) {
            i = a; j = b;
            if (i == j) return true;
            const auto values = arr.get_two_existing(r, i, j);
            a = values.first; b = values.second;
        }
        while (a >= 0) { i = a; if (i == j) return true; a = arr.get_existing(r, i); }
        while (b >= 0) { j = b; if (i == j) return true; b = arr.get_existing(r, j); }
        return i == j;
    }
    bool same(int i, int j) const { return same(i, j, version_); }
    bool issame(int i, int j, Version r) const { return same(i, j, r); }
    bool issame(int i, int j) const { return same(i, j); }
    bool unite(int i, int j, Version r) {
        const auto values = find_pair(i, j, r);
        auto [a, sa] = values.first; auto [b, sb] = values.second;
        if (a == b) { version_ = arr.root = r; return false; }
        if (sa > sb) { std::swap(a, b); std::swap(sa, sb); }
        r = arr.update_two(r, static_cast<std::uint64_t>(a), sa + sb,
                           static_cast<std::uint64_t>(b), a, arr.levels_);
        version_ = arr.root = r; return true;
    }
    bool unite(int i, int j) { return unite(i, j, version_); }
    bool merge(int i, int j, Version r) { return unite(i, j, r); }
    bool merge(int i, int j) { return unite(i, j); }
    Version version() const noexcept { return version_; }
    void restore(Version r) { check_version(r); arr.restore(r); version_ = r; }
    int component_count(Version r) const {
        check_version(r);
        int count = 0; for (int i = 0; i < size(); ++i) count += arr.get_unchecked(r, i) < 0; return count;
    }
    int component_count() const { return component_count(version_); }
    std::vector<std::vector<int>> groups(Version r) const {
        check_version(r);
        std::vector<int> leaders(size()), count(size(), 0), slot(size());
        if constexpr (PersistentArray<int>::compact_nodes) {
            for (int i = 0; i < size(); ++i) ++count[leaders[i] = leader_existing_parents(i, r)];
        } else {
            for (int i = 0; i < size(); ++i) ++count[leaders[i] = find(i, r)];
        }
        std::vector<std::vector<int>> result;
        for (int i = 0; i < size(); ++i) if (count[i]) {
            slot[i] = static_cast<int>(result.size()); result.emplace_back(); result.back().reserve(count[i]);
        }
        for (int i = 0; i < size(); ++i) result[slot[leaders[i]]].push_back(i);
        return result;
    }
    std::vector<std::vector<int>> groups() const { return groups(version_); }
private:
    // groupsで版・添字を確かめた後に使う。親の配列経路は同じ版で明示更新済み。
    int leader_existing_parents(int i, Version r) const {
        int value = arr.get_unchecked(r, i);
        while (value >= 0) { i = value; value = arr.get_existing(r, i); }
        return i;
    }
    void check_version([[maybe_unused]] Version r) const {
#ifndef SKIP_RUNTIME_CHECKS
        if (!r && size() != 0) throw std::invalid_argument("PersistentUnionFind: null version");
        arr.check_root(r);
#endif
    }
    std::pair<std::pair<int,int>, std::pair<int,int>> find_pair(int i, int j, Version r) const {
        check_version(r); arr.check_index(i); arr.check_index(j);
        auto [a, b] = arr.get_two_unchecked(r, i, j);
        while (a >= 0 && b >= 0) {
            i = a; j = b;
            const auto values = arr.get_two_existing(r, i, j);
            a = values.first; b = values.second;
        }
        while (a >= 0) { i = a; a = arr.get_existing(r, i); }
        while (b >= 0) { j = b; b = arr.get_existing(r, j); }
        return {{i, a}, {j, b}};
    }
    static std::int64_t checked_size(std::size_t n) {
        if (n > static_cast<std::size_t>(std::numeric_limits<int>::max()))
            throw std::length_error("PersistentUnionFind: too many vertices");
        return static_cast<std::int64_t>(n);
    }
};
#endif

} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1
Back to top page