Complete the code to initialize the parent of each element to itself in the Union Find structure.
for (int i = 0; i < n; i++) { parent[i] = [1]; }
Each element is initially its own parent, so parent[i] = i; sets this up.
Complete the code to find the root parent of element x with path compression.
int find(int x) {
if (parent[x] != x) {
parent[x] = [1];
}
return parent[x];
}Path compression sets parent[x] to the root parent found by recursively calling find(parent[x]).
Fix the error in the union function to correctly merge two sets by rank.
void unionSets(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
if (rank[a] < rank[b])
parent[a] = [1];
else if (rank[a] > rank[b])
parent[b] = a;
else {
parent[b] = a;
rank[a]++;
}
}
}When rank[a] < rank[b], set parent[a] = b; to attach the smaller tree under the bigger one, and vice versa.
Fill both blanks to implement union by size instead of rank.
void unionSets(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
if (size[a] < size[b]) {
parent[a] = [1];
size[b] += size[a];
} else {
parent[b] = [2];
size[a] += size[b];
}
}
}When size[a] < size[b], attach a under b by parent[a] = b;. Otherwise, attach b under a by parent[b] = a;.
Fill all three blanks to create a map of each element to its root parent only if the root is greater than 0.
std::map<int, int> rootMap; for (int i = 1; i <= n; i++) { if ([3] > 0) { rootMap[[1]] = [2]; } }
Map keys are elements i, values are their root parents find(i), and the condition checks if root parent is > 0.
