Created
September 16, 2021 16:14
-
-
Save abhishek2x/2c4e2618103a1a30c7d80501e4e956e4 to your computer and use it in GitHub Desktop.
Template for Union Find Algorithm used in Graph related problems.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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