union_find.hh 1014 Bytes
Newer Older
Philip Trettner's avatar
Philip Trettner committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#pragma once

#include <vector>

namespace polymesh
{
namespace detail
{
struct disjoint_set
{
public:
    disjoint_set(int size) : entries(size)
    {
        for (auto i = 0; i < size; ++i)
        {
            auto& e = entries[i];
            e.parent = i;
            e.size = 1;
        }
    }

    int find(int idx)
    {
        auto& e = entries[idx];
        if (e.parent != idx)
            e.parent = find(e.parent);
        return e.parent;
    }

    bool do_union(int x, int y)
    {
        // union by size
        auto x_root = find(x);
        auto y_root = find(y);

        if (x_root == y_root)
            return false;

        if (entries[x_root].size < entries[y_root].size)
            std::swap(x_root, y_root);
        // |X| > |Y|

        entries[y_root].parent = x_root;
        entries[x_root].size += entries[y_root].size;

        return true;
    }

private:
    struct entry
    {
        int parent;
        int size;
    };

private:
    std::vector<entry> entries;
};
}
}