Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@abhishek2x
Created September 16, 2021 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhishek2x/2c4e2618103a1a30c7d80501e4e956e4 to your computer and use it in GitHub Desktop.
Save abhishek2x/2c4e2618103a1a30c7d80501e4e956e4 to your computer and use it in GitHub Desktop.
Template for Union Find Algorithm used in Graph related problems.
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];
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment