Complete the code to initialize the parent array for Union-Find.
int[] parent = new int[n]; for (int i = 0; i < n; i++) { parent[i] = [1]; }
Each node is initially its own parent, so we assign parent[i] = i.
Complete the code to find the root parent of a node with path compression.
int Find(int[] parent, int x) {
if (parent[x] != x) {
parent[x] = [1];
}
return parent[x];
}Path compression sets parent[x] to the root found by recursively calling Find.
Fix the error in the union operation to merge two sets correctly.
void Union(int[] parent, int x, int y) {
int rootX = Find(parent, x);
int rootY = Find(parent, y);
if (rootX != rootY) {
parent[[1]] = rootY;
}
}We set the parent of rootX to rootY to merge the sets.
Fill both blanks to check if adding an edge creates a cycle and to add the edge weight.
foreach (var edge in edges) { if (Find(parent, edge.u) [1] Find(parent, edge.v)) { Union(parent, edge.u, edge.v); totalWeight [2]= edge.weight; } }
We add the edge only if the roots are different (no cycle), and add the edge weight to totalWeight.
Fill all three blanks to sort edges by weight and initialize variables for Kruskal's algorithm.
edges.Sort((a, b) => a.[1].CompareTo(b.[2])); int n = [3]; int[] parent = new int[n];
We sort edges by their weight property, and initialize n with the number of nodes.
