competitive_library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub knshnb/competitive_library

:heavy_check_mark: src/DataStructure/QuickFind.hpp

概要

素集合データ構造のマージを高速化するテクニック。 n要素の集合のマージを何度も行う際に、サイズの小さい方を大きい方にマージすることでのべ移動回数がO(n log n)回で抑えられる。 これは、各要素に注目すると、別の集合に移動されるたびに属する集合のサイズが2倍以上になるのでO(log n)回しか移動されないことからわかる。

データをマージする一般的なテク(通称、マージテク)とも呼ばれる。 名前はiwiwiさんのブログに由来するが、消えてしまった…。 アカデミア用語はWeighted-Union Heuristic。

Verified with

Code

/// @docs src/DataStructure/QuickFind.md
struct QuickFind {
    std::vector<int> belong_to;
    std::vector<std::vector<int>> groups;
    QuickFind(int n) : belong_to(n), groups(n, std::vector<int>(1)) {
        std::iota(belong_to.begin(), belong_to.end(), 0);
        for (int i = 0; i < n; i++) groups[i][0] = i;
    }
    void unite(int x, int y) {
        x = belong_to[x], y = belong_to[y];
        if (x == y) return;
        if (groups[x].size() < groups[y].size()) std::swap(x, y);
        // yをxにマージ
        for (int v : groups[y]) belong_to[v] = x;
        groups[x].insert(groups[x].end(), groups[y].begin(), groups[y].end());
        groups[y].clear();
    }
    bool is_same(int x, int y) { return belong_to[x] == belong_to[y]; }
};
#line 1 "src/DataStructure/QuickFind.hpp"
/// @docs src/DataStructure/QuickFind.md
struct QuickFind {
    std::vector<int> belong_to;
    std::vector<std::vector<int>> groups;
    QuickFind(int n) : belong_to(n), groups(n, std::vector<int>(1)) {
        std::iota(belong_to.begin(), belong_to.end(), 0);
        for (int i = 0; i < n; i++) groups[i][0] = i;
    }
    void unite(int x, int y) {
        x = belong_to[x], y = belong_to[y];
        if (x == y) return;
        if (groups[x].size() < groups[y].size()) std::swap(x, y);
        // yをxにマージ
        for (int v : groups[y]) belong_to[v] = x;
        groups[x].insert(groups[x].end(), groups[y].begin(), groups[y].end());
        groups[y].clear();
    }
    bool is_same(int x, int y) { return belong_to[x] == belong_to[y]; }
};
Back to top page