Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the Union-Find (or Disjoint Set) data structure in STL?

I would have expected such a useful data structure to be included in the C++ Standard Library but I can't seem to find it.

like image 643
Ritwik Biswas Avatar asked Apr 22 '17 16:04

Ritwik Biswas


2 Answers

No. I written a simple implementation. It's very extensible.

struct DisjointSet {
    vector<int> parent;
    vector<int> size;

    DisjointSet(int maxSize) {
        parent.resize(maxSize);
        size.resize(maxSize);
        for (int i = 0; i < maxSize; i++) {
            parent[i] = i;
            size[i] = 1;
        }
    }

    int find_set(int v) {
        if (v == parent[v])
            return v;
        return parent[v] = find_set(parent[v]);
    }

    void union_set(int a, int b) {
        a = find_set(a);
        b = find_set(b);
        if (a != b) {
            if (size[a] < size[b])
                swap(a, b);
            parent[b] = a;
            size[a] += size[b];
        }
    }
};

And the usage as follows.

void solve() {
    int n;
    cin >> n;
    DisjointSet S(n);  // Initializing with maximum Size
    S.union_set(1, 2);
    S.union_set(3, 7);
    int parent = S.find_set(1);  // root of 1
}
like image 130
Appaji Chintimi Avatar answered Sep 20 '22 20:09

Appaji Chintimi


It is not, but there is one in boost: http://www.boost.org/doc/libs/1_64_0/libs/disjoint_sets/disjoint_sets.html, so if you want an off-the-shelf implementation I'd recommend this.

like image 31
Nir Friedman Avatar answered Sep 18 '22 20:09

Nir Friedman