Skip to content

Instantly share code, notes, and snippets.

@HirbodBehnam
Created January 13, 2022 11:00
Show Gist options
  • Save HirbodBehnam/050b61946f0ec0d9d9747974e08ac7c7 to your computer and use it in GitHub Desktop.
Save HirbodBehnam/050b61946f0ec0d9d9747974e08ac7c7 to your computer and use it in GitHub Desktop.
Simple disjoint set which I don't know if it works or not.
// from https://github.com/spakin/disjoint
class disjoint_set {
private:
typedef struct {
int rank;
int parent;
} element;
vector<element> set_list;
public:
explicit disjoint_set(int size) {
set_list.resize(size);
for (int i = 0; i < size; i++)
set_list[i].parent = i;
}
int find(int e) {
while (set_list[e].parent != e) {
set_list[e].parent = set_list[set_list[e].parent].parent;
e = set_list[e].parent;
}
return e;
}
void union_set(int e1, int e2) {
int e1Root = find(e1);
int e2Root = find(e2);
if (e1Root == e2Root)
return;
if (set_list[e1].rank < set_list[e2].rank)
set_list[e1].parent = e2;
else if (set_list[e1].rank > set_list[e2].rank)
set_list[e2].parent = e1;
else {
set_list[e2].parent = e1;
set_list[e1].rank++;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment