sirkit-cpp-library

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

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

動的Union Find

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

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

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

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

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

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

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

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

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

int全域のキーを扱い、各キーを使った時点で登録するUnion Findです。負の値やINT_MIN・INT_MAXも使えます。利用側で連続した添字に変換する必要はありません。

以下、Nは登録済みキー数です。

APIと前提

DynamicUnionFind

DynamicUnionFind();
explicit DynamicUnionFind(std::size_t expected_nodes);

空の状態で構築します。expected_nodesを渡すと、その件数分の容量を予約します。

制約: 予約件数はINT_MAX以下。

計算量: 空はO(1)、予約は予約容量に比例。

add

bool add(int key);

単独成分として登録し、新規登録ならtrueを返します。

制約: 登録数はINT_MAX以下。

計算量: ハッシュの期待償却O(1)。

find

int find(int key);

代表キーを返します。未知のキーは自動登録します。

制約: 登録数はINT_MAX以下。

計算量: 期待償却O(α(N+1))。

same

int same(int x, int y);

同じ成分なら1、異なれば0を返します。未知キーは自動登録します。

制約: 登録数はINT_MAX以下。

計算量: 期待償却O(α(N+1))。

unite

int unite(int x, int y);
template<class F> int unite(int x, int y, const F& callback);

成分をサイズに基づいて併合し、結合できたら1、すでに同じ成分なら0を返します。callback版では、併合したときだけ新旧の代表をcallbackに渡します。

制約: 登録数はINT_MAX以下。callbackで本体を破壊しないこと。

計算量: 期待償却O(α(N+1))とcallbackの費用。

size

int size(int key);

所属成分の要素数を返します。未知のキーは自動登録します。

制約: 登録数はINT_MAX以下。

計算量: 期待償却O(α(N+1))。

data

int data(int key);

根なら負のサイズ、非根なら親キーを返します。未知のキーは自動登録します。

制約: 負の親キーとの区別には使わず、代表はfindで取得します。

計算量: 期待償却O(α(N+1))。

contains

bool contains(int key) const;

登録済みならtrueです。自動登録しません。

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

計算量: 期待O(1)。

node_count

std::size_t node_count() const noexcept;

登録済みキーの個数を返します。

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

計算量: O(1)。

component_count

std::size_t component_count() const noexcept;

登録済み成分数を返します。

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

計算量: O(1)。

empty

bool empty() const noexcept;

登録がなければtrueです。

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

計算量: O(1)。

groups

std::vector<std::vector<int>> groups();

成分ごとのキー一覧を返します。成分間の順は未規定です。

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

計算量: O(N α(N+1))、全独立/全連結ではO(N+1)。

reserve

void reserve(std::size_t expected_nodes);

登録状態を保ち指定件数分の容量を予約します。

制約: 予約件数はINT_MAX以下。

計算量: 再確保前後の容量に比例する期待時間。

clear

void clear();

全登録を消し、確保済み容量を再利用します。

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

計算量: 保持する配列・表の容量に比例。

find・same・size・data・uniteは、未知のキーを単独成分として自動登録します。登録数はINT_MAX以下です。内部の容量上限はSKIP_RUNTIME_CHECKSでも維持します。

方式と計算量

ハッシュ検索は期待O(1)、併合・探索は償却O(α(N))です。containsは期待O(1)、件数取得はO(1)、groupsはO(N α(N))、全独立または全連結ならO(N+1)です。使用領域は登録数と予約容量に比例します。

コピーは独立した複製を作り、コピー代入の確保失敗時は元の内容を維持します。move元は空になり、再利用できます。1キーの登録に失敗したとき、そのキーは登録されず、既存の連結関係は保ちます。複数キーを扱う操作では、それまでに成功した登録は残ります。groupsの確保失敗時も登録と連結関係は保ちます。成功したgroupsは親を短縮するため、data(k)の返す親キーが変わる場合があります。

完全な使用例

ソースのAPI注記
[DynamicUnionFind]
intの全域をキーにできる。要素は問い合わせ時に自動登録する。
ハッシュ表の検索は期待O(1)、併合・探索は償却O(α(N))、空間O(N)。
DynamicUnionFind(): 空で構築する。登録数はINT_MAXまで。
DynamicUnionFind(n): n要素分の容量を予約して空で構築する。
コピーは独立した複製。ムーブ元は空になり、再利用できる。
data(k): 自動登録し、根なら負の要素数、非根なら親のキーを返す。
find(k): 自動登録し、所属する連結成分の代表キーを返す。
unite(x, y): 自動登録してサイズで併合し、併合したときtrueを返す。
unite(x, y, f): 併合後にf(新しい代表キー, 吸収した代表キー)を1回呼ぶ。
size(k): 自動登録し、kが所属する連結成分の要素数を返す。
same(x, y): 自動登録し、同じ連結成分ならtrueを返す。
add(k): 未登録のキーを単独の成分として追加し、追加したときtrueを返す。
contains(k): キーが登録済みならtrueを返す。自動登録しない。
node_count(): 登録済みのキーの個数をO(1)で返す。
component_count(): 登録済みの連結成分数をO(1)で返す。
empty(): 登録済みのキーがなければtrueを返す。
reserve(n): n要素分を予約する。成分や登録状態は変えない。
groups(): 全成分のキー一覧をO(N α(N))で返す。成分間の順序は未規定。
clear(): 全登録を消去する。確保済みの容量は再利用する。
dataの負の返値は、負の親キーとの区別を保証しない。判定にはfindを使う。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Dynamic structures / Hash / Heap / Treap local checks dynamic_hash_local.cpp ローカル補足 —
Unionfind dynamic_union_find.cpp 現行未照合・要再提出 AC

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

ローカル・CI検査

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

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

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

Verified with

Code

// SPDX-License-Identifier: CC0-1.0 AND LicenseRef-SplitMix64-Public-Domain
// SplitMix64部分(InternalHashMap::mix)はCC0ではなく、原著者のPD提供声明・無条件許諾に従う。
// CC0-1.0はそれ以外の部分に適用する。SplitMix64の提供条件:
// https://github.com/reinsirk/sirkit-cpp-library/blob/main/LICENSES/LicenseRef-SplitMix64-Public-Domain.txt
// 参考: https://nyaannyaan.github.io/library/data-structure/dynamic-union-find.hpp
// Original Source (InternalHashMap): https://nyaannyaan.github.io/library/data-structure/hash-map-variable-length.hpp.html
// Original Source (mix): https://prng.di.unimi.it/splitmix64.c
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/dynamic_union_find.md
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/internal_hash_map.md
//
// API一覧
// [DynamicUnionFind]
// intの全域をキーにできる。要素は問い合わせ時に自動登録する。
// ハッシュ表の検索は期待O(1)、併合・探索は償却O(α(N))、空間O(N)。
// DynamicUnionFind(): 空で構築する。登録数はINT_MAXまで。
// DynamicUnionFind(n): n要素分の容量を予約して空で構築する。
// コピーは独立した複製。ムーブ元は空になり、再利用できる。
// data(k): 自動登録し、根なら負の要素数、非根なら親のキーを返す。
// find(k): 自動登録し、所属する連結成分の代表キーを返す。
// unite(x, y): 自動登録してサイズで併合し、併合したときtrueを返す。
// unite(x, y, f): 併合後にf(新しい代表キー, 吸収した代表キー)を1回呼ぶ。
// size(k): 自動登録し、kが所属する連結成分の要素数を返す。
// same(x, y): 自動登録し、同じ連結成分ならtrueを返す。
// add(k): 未登録のキーを単独の成分として追加し、追加したときtrueを返す。
// contains(k): キーが登録済みならtrueを返す。自動登録しない。
// node_count(): 登録済みのキーの個数をO(1)で返す。
// component_count(): 登録済みの連結成分数をO(1)で返す。
// empty(): 登録済みのキーがなければtrueを返す。
// reserve(n): n要素分を予約する。成分や登録状態は変えない。
// groups(): 全成分のキー一覧をO(N α(N))で返す。成分間の順序は未規定。
// clear(): 全登録を消去する。確保済みの容量は再利用する。
// dataの負の返値は、負の親キーとの区別を保証しない。判定にはfindを使う。


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

#include <algorithm>
#include <bit>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__i386__) || defined(__x86_64__)) && (defined(__GNUC__) || defined(__clang__))
#include <immintrin.h>
#endif


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_INTERNAL_HASH_MAP_DEFINED
#define SIRKIT_INTERNAL_HASH_MAP_DEFINED
namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ {
template <class Key, class Val, bool Packed = false, unsigned Denominator = 5>
class InternalHashMap {
    static_assert(std::is_integral_v<Key> &&
                  std::is_same_v<Key, std::remove_cv_t<Key>> &&
                  !std::is_same_v<Key, bool> &&
                  sizeof(Key) <= sizeof(std::uint64_t),
                  "InternalHashMap: Key must be an integer of at most 64 bits");
    static_assert(Denominator >= 2 && Denominator <= 8);
    struct Value { Val value{}; };
    std::vector<Key> keys_;
    std::vector<Value> values_;
    using Flag = std::conditional_t<Packed, bool, std::uint8_t>;
    std::vector<Flag> used_;
    std::size_t size_ = 0;
    Val default_value_{};
    std::uint64_t salt_ = 0;
    unsigned shift_ = 61;

    static std::uint64_t mix(std::uint64_t x) noexcept {
        x = (x ^ (x >> 30)) * UINT64_C(0xbf58476d1ce4e5b9);
        x = (x ^ (x >> 27)) * UINT64_C(0x94d049bb133111eb);
        return x ^ (x >> 31);
    }

    static std::uint64_t initial_salt() noexcept {
        static const std::uint64_t value = mix(static_cast<std::uint64_t>(
            std::chrono::steady_clock::now().time_since_epoch().count())) | std::uint64_t{1};
        return value;
    }

    std::size_t hash(Key key) const noexcept {
        return static_cast<std::size_t>((static_cast<std::uint64_t>(key) * salt_) >> shift_);
    }

    std::size_t max_capacity() const noexcept {
        return std::bit_floor(std::min({keys_.max_size(), values_.max_size(), used_.max_size()}));
    }

    static std::size_t doubled_capacity(std::size_t capacity, std::size_t maximum) {
        if (capacity > maximum / 2)
            throw std::length_error("InternalHashMap: capacity overflow");
        return capacity * 2;
    }

    static std::uint32_t occupied8(const std::uint8_t* flags) noexcept {
        std::uint64_t word;
        std::memcpy(&word, flags, sizeof(word));
        if constexpr (std::endian::native == std::endian::big) word = std::byteswap(word);
        else if constexpr (std::endian::native != std::endian::little) {
            word = 0;
            for (unsigned j = 0; j < 8; ++j) word |= std::uint64_t(flags[j]) << (8 * j);
        }
        return static_cast<std::uint32_t>((word * UINT64_C(0x0102040810204080)) >> 56);
    }
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__i386__) || defined(__x86_64__)) && (defined(__GNUC__) || defined(__clang__))
    [[gnu::target("avx2")]] static std::uint32_t occupied32(const std::uint8_t* flags) noexcept {
        const auto x = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(flags));
        return ~static_cast<std::uint32_t>(_mm256_movemask_epi8(_mm256_cmpeq_epi8(x, _mm256_setzero_si256())));
    }
    static bool supports_avx2() noexcept {
        static const bool yes = [] { __builtin_cpu_init(); return __builtin_cpu_supports("avx2"); }();
        return yes;
    }
#endif

    void rehash(std::size_t capacity) {
        if (salt_ == 0) salt_ = initial_salt();
        if (capacity > max_capacity())
            throw std::length_error("InternalHashMap: capacity overflow");
        const unsigned next_shift = 64 - std::countr_zero(capacity);
        std::vector<Key> keys(capacity);
        std::vector<Value> values(capacity);
        std::vector<Flag> used(capacity, 0);
        if (size_ != 0) {
            if constexpr (!Packed) {
                if (used_.size() >= 64) {
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__i386__) || defined(__x86_64__)) && (defined(__GNUC__) || defined(__clang__))
                    if (supports_avx2()) {
                        for (std::size_t first = 0; first < used_.size(); first += 32) {
                            auto mask = occupied32(used_.data() + first);
                            while (mask != 0) {
                                const std::size_t i = first + std::countr_zero(mask);
                                mask &= mask - 1;
                                std::size_t p = static_cast<std::size_t>((static_cast<std::uint64_t>(keys_[i]) * salt_) >> next_shift);
                                while (used[p]) p = (p + 1) & (capacity - 1);
                                keys[p] = keys_[i];
                                values[p].value = values_[i].value;
                                used[p] = 1;
                            }
                        }
                    } else
#endif
                    {
                        for (std::size_t first = 0; first < used_.size(); first += 8) {
                            auto mask = occupied8(used_.data() + first);
                            while (mask != 0) {
                                const std::size_t i = first + std::countr_zero(mask);
                                mask &= mask - 1;
                                std::size_t p = static_cast<std::size_t>((static_cast<std::uint64_t>(keys_[i]) * salt_) >> next_shift);
                                while (used[p]) p = (p + 1) & (capacity - 1);
                                keys[p] = keys_[i];
                                values[p].value = values_[i].value;
                                used[p] = 1;
                            }
                        }
                    }
                } else {
                    for (std::size_t i = 0; i < used_.size(); ++i) {
                        if (!used_[i]) continue;
                        std::size_t p = static_cast<std::size_t>((static_cast<std::uint64_t>(keys_[i]) * salt_) >> next_shift);
                        while (used[p]) p = (p + 1) & (capacity - 1);
                        keys[p] = keys_[i];
                        values[p].value = values_[i].value;
                        used[p] = 1;
                    }
                }
            } else {
                for (std::size_t i = 0; i < used_.size(); ++i) {
                    if (!used_[i]) continue;
                    std::size_t p = static_cast<std::size_t>((static_cast<std::uint64_t>(keys_[i]) * salt_) >> next_shift);
                    while (used[p]) p = (p + 1) & (capacity - 1);
                    keys[p] = keys_[i];
                    values[p].value = values_[i].value;
                    used[p] = 1;
                }
            }
        }
        keys_.swap(keys);
        values_.swap(values);
        used_.swap(used);
        shift_ = next_shift;
    }

public:
    InternalHashMap() noexcept(std::is_nothrow_default_constructible_v<Val>) = default;
    InternalHashMap(const InternalHashMap&) = default;
    InternalHashMap(InternalHashMap&& other) noexcept(std::is_nothrow_default_constructible_v<Val> &&
                                    std::is_nothrow_swappable_v<Val>) : InternalHashMap() { swap(other); }
    InternalHashMap& operator=(InternalHashMap other) {
        swap(other);
        return *this;
    }

    void swap(InternalHashMap& other) noexcept(std::is_nothrow_swappable_v<Val>) {
        using std::swap;
        swap(default_value_, other.default_value_);
        keys_.swap(other.keys_);
        values_.swap(other.values_);
        used_.swap(other.used_);
        swap(size_, other.size_);
        swap(salt_, other.salt_);
        swap(shift_, other.shift_);
    }

    void reserve(std::size_t n) {
        if (n <= keys_.size() - keys_.size() / Denominator) return;
        std::size_t capacity = std::max(std::size_t{8}, keys_.size());
        while (n > capacity - capacity / Denominator)
            capacity = doubled_capacity(capacity, max_capacity());
        rehash(capacity);
    }

    void reallocate() {
        if (keys_.empty()) {
            rehash(8);
        } else {
            rehash(doubled_capacity(keys_.size(), max_capacity()));
        }
    }

    Val& operator[](Key key) {
        if (keys_.empty()) reallocate();
        std::size_t p = hash(key);
        while (used_[p]) {
            if (keys_[p] == key) return values_[p].value;
            p = (p + 1) & (keys_.size() - 1);
        }
        if (size_ == keys_.size() - keys_.size() / Denominator) {
            reallocate();
            p = hash(key);
            while (used_[p]) p = (p + 1) & (keys_.size() - 1);
        }
        keys_[p] = key;
        values_[p].value = default_value_;
        used_[p] = 1;
        ++size_;
        return values_[p].value;
    }

    template <class F> Val& find_or_emplace(Key key, F&& factory) {
        if (keys_.empty()) reallocate();
        std::size_t p = hash(key);
        while (used_[p]) {
            if (keys_[p] == key) return values_[p].value;
            p = (p + 1) & (keys_.size() - 1);
        }
        if (size_ == keys_.size() - keys_.size() / Denominator) {
            reallocate();
            p = hash(key);
            while (used_[p]) p = (p + 1) & (keys_.size() - 1);
        }
        values_[p].value = std::forward<F>(factory)();
        keys_[p] = key;
        used_[p] = 1;
        ++size_;
        return values_[p].value;
    }

    const Val* find(const Key& key) const noexcept {
        if (keys_.empty()) return nullptr;
        return find_nonempty(key);
    }
    const Val* find_nonempty(const Key& key) const noexcept {
        std::size_t p = hash(key);
        while (used_[p]) {
            if (keys_[p] == key) return &values_[p].value;
            p = (p + 1) & (keys_.size() - 1);
        }
        return nullptr;
    }
    Val* find(const Key& key) noexcept {
        return const_cast<Val*>(static_cast<const InternalHashMap&>(*this).find(key));
    }

    std::vector<std::pair<Key, Val>> enumerate() const {
        std::vector<std::pair<Key, Val>> result;
        if (empty()) return result;
        result.reserve(size_);
        for (std::size_t i = 0; i < used_.size(); ++i)
            if (used_[i]) result.emplace_back(keys_[i], values_[i].value);
        return result;
    }

    template <class F> void for_each(F&& f) const {
        if (empty()) return;
        for (std::size_t i = 0; i < used_.size(); ++i)
            if (used_[i]) f(keys_[i], values_[i].value);
    }

    [[nodiscard]] bool contains(Key key) const noexcept { return find(key) != nullptr; }
    [[nodiscard]] bool contain(Key key) const noexcept { return contains(key); }
    [[nodiscard]] int count(Key key) const noexcept { return contains(key) ? 1 : 0; }
    void clear() noexcept {
        if (empty()) return;
        std::fill(used_.begin(), used_.end(), Flag{0});
        size_ = 0;
    }
    void release() noexcept {
        decltype(keys_){}.swap(keys_);
        decltype(values_){}.swap(values_);
        decltype(used_){}.swap(used_);
        size_ = 0;
        shift_ = 61;
    }
    std::size_t capacity() const noexcept { return keys_.size(); }
    double load_factor() const noexcept {
        return capacity() == 0 ? 0.0 : static_cast<double>(size_) / capacity();
    }
    std::size_t size() const noexcept { return size_; }
    bool empty() const noexcept { return size_ == 0; }
    void set_default(const Val& value) { default_value_ = value; }
};

}  // namespace reinsirk::detail
#endif  // SIRKIT_INTERNAL_HASH_MAP_DEFINED


#ifndef SIRKIT_DYNAMIC_UNION_FIND_DEFINED
#define SIRKIT_DYNAMIC_UNION_FIND_DEFINED
class DynamicUnionFind {
    struct Node {
        int key;
        // 根なら負のサイズ、非根なら親の添字。キーの符号とは独立。
        int parent;
    };
    /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::InternalHashMap<int, int, false, 4> indices_;
    std::vector<Node> nodes_;
    std::size_t components_ = 0;

    static void check_capacity(std::size_t count) {
        if (count > static_cast<std::size_t>(std::numeric_limits<int>::max()))
            throw std::length_error("DynamicUnionFind: too many nodes");
    }

#if defined(__GNUC__) && !defined(__clang__)
    int index_for(int key) {
        return indices_.find_or_emplace(key, [&] {
            check_capacity(nodes_.size() + 1);
            const int index = static_cast<int>(nodes_.size());
            nodes_.push_back(Node{key, -1});
            ++components_;
            return index;
        });
    }
#else
    int index_for(int key) {
        if (const auto* index = indices_.find(key)) return *index;
        check_capacity(nodes_.size() + 1);
        const int index = static_cast<int>(nodes_.size());
        nodes_.push_back(Node{key, -1});
        try {
            indices_[key] = index;
        } catch (...) {
            nodes_.pop_back();
            throw;
        }
        ++components_;
        return index;
    }
#endif

    int root_index(int index) noexcept {
        while (nodes_[index].parent >= 0) {
            const int parent = nodes_[index].parent;
            if (nodes_[parent].parent < 0) return parent;
            nodes_[index].parent = nodes_[parent].parent;
            index = nodes_[index].parent;
        }
        return index;
    }

    std::pair<int, int> merge_roots(int x, int y) {
#if defined(__GNUC__) && !defined(__clang__)
        const int ix = index_for(x);
        const int iy = index_for(y);
        int a = root_index(ix);
        int b = root_index(iy);
#else
        int a = root_index(index_for(x));
        int b = root_index(index_for(y));
#endif
        if (a == b) return {-1, -1};
        if (nodes_[a].parent > nodes_[b].parent) std::swap(a, b);
        // 各成分のサイズの合計は、上限検査済みの登録数以下。
        nodes_[a].parent += nodes_[b].parent;
        nodes_[b].parent = a;
        --components_;
        return {a, b};
    }

    std::vector<std::vector<int>> trivial_groups() {
        std::vector<std::vector<int>> result;
        result.reserve(components_);
        if (components_ == nodes_.size()) {
            for (const auto& node : nodes_) result.emplace_back(std::size_t{1}, node.key);
        } else {
            result.emplace_back(); result.back().reserve(nodes_.size());
            const int root = root_index(0);
            for (std::size_t i = 0; i < nodes_.size(); ++i) {
                result[0].push_back(nodes_[i].key);
                if (static_cast<int>(i) != root) nodes_[i].parent = root;
            }
        }
        return result;
    }

public:
    DynamicUnionFind() = default;
    explicit DynamicUnionFind(std::size_t expected_nodes) { reserve(expected_nodes); }
    DynamicUnionFind(const DynamicUnionFind&) = default;
    DynamicUnionFind& operator=(const DynamicUnionFind& other) {
        if (this == &other) return *this;
        DynamicUnionFind copy(other);
        indices_.swap(copy.indices_);
        nodes_.swap(copy.nodes_);
        std::swap(components_, copy.components_);
        return *this;
    }
    DynamicUnionFind(DynamicUnionFind&& other) noexcept
        : indices_(std::move(other.indices_)), nodes_(std::move(other.nodes_)),
          components_(std::exchange(other.components_, 0)) {
        other.nodes_.clear();
    }
    DynamicUnionFind& operator=(DynamicUnionFind&& other) noexcept {
        if (this == &other) return *this;
        indices_ = std::move(other.indices_);
        nodes_ = std::move(other.nodes_);
        components_ = std::exchange(other.components_, 0);
        other.nodes_.clear();
        return *this;
    }

    int data(int key) {
        const int index = index_for(key);
        return nodes_[index].parent < 0 ? nodes_[index].parent
                                             : nodes_[nodes_[index].parent].key;
    }

    int find(int key) { return nodes_[root_index(index_for(key))].key; }

    int unite(int x, int y) { return merge_roots(x, y).first != -1; }

    template <class F>
    int unite(int x, int y, const F& callback) {
        const auto [root, child] = merge_roots(x, y);
        if (root == -1) return false;
        callback(nodes_[root].key, nodes_[child].key);
        return true;
    }

    int size(int key) { return -nodes_[root_index(index_for(key))].parent; }
#if defined(__GNUC__) && !defined(__clang__)
    int same(int x, int y) {
        const int ix = index_for(x);
        const int iy = index_for(y);
        return root_index(ix) == root_index(iy);
    }
#else
    int same(int x, int y) { return find(x) == find(y); }

#endif

    bool add(int key) {
        const auto before = nodes_.size();
        index_for(key);
        return before != nodes_.size();
    }

    bool contains(int key) const {
        return indices_.contains(key);
    }
    std::size_t node_count() const noexcept { return nodes_.size(); }
    std::size_t component_count() const noexcept { return components_; }
    bool empty() const noexcept { return nodes_.empty(); }

    void reserve(std::size_t expected_nodes) {
        check_capacity(expected_nodes);
        nodes_.reserve(expected_nodes);
        indices_.reserve(expected_nodes);
    }

    std::vector<std::vector<int>> groups() {
#if defined(__GNUC__) && !defined(__clang__)
        if (nodes_.empty()) return {};
#endif
        if (components_ == nodes_.size() || components_ == 1) return trivial_groups();
        std::vector<std::vector<int>> result;
        result.reserve(components_);
#if defined(__GNUC__) && !defined(__clang__)
        using GroupIndex = std::make_unsigned_t<int>;
        // 根の添字だけを読み、全て直後の走査で代入する。
        std::array<GroupIndex, 32> local_indices;
        std::unique_ptr<GroupIndex[]> large_indices;
        GroupIndex* group_index = local_indices.data();
        if (nodes_.size() > local_indices.size()) {
            large_indices = std::make_unique_for_overwrite<GroupIndex[]>(nodes_.size());
            group_index = large_indices.get();
        }
#else
        std::vector<std::size_t> group_index(nodes_.size());
#endif
        for (std::size_t i = 0; i < nodes_.size(); ++i) {
            if (nodes_[i].parent >= 0) continue;
#if defined(__GNUC__) && !defined(__clang__)
            group_index[i] = static_cast<GroupIndex>(result.size());
#else
            group_index[i] = result.size();
#endif
            result.emplace_back();
            result.back().reserve(static_cast<std::size_t>(-nodes_[i].parent));
        }
        for (std::size_t i = 0; i < nodes_.size(); ++i)
            result[group_index[root_index(static_cast<int>(i))]].push_back(nodes_[i].key);
        return result;
    }

    void clear() {
        indices_.clear();
        nodes_.clear();
        components_ = 0;
    }
};
#endif

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