Complete the code to find the root parent of a node in Union Find.
fn find(parent: &mut Vec<usize>, x: usize) -> usize {
if parent[x] != x {
return [1];
}
x
}parent[x] directly without recursion.x immediately without checking parent.The find function recursively finds the root parent of x by calling itself on parent[x] until it reaches the root where parent[x] == x.
Complete the code to apply path compression in the find function.
fn find(parent: &mut Vec<usize>, x: usize) -> usize {
if parent[x] != x {
parent[x] = [1];
}
parent[x]
}parent[x] to x instead of the root.parent[x] at all.Path compression updates parent[x] to the root parent by recursively calling find on parent[x]. This flattens the tree for faster future queries.
Fix the error in the union function to correctly merge two sets.
fn union(parent: &mut Vec<usize>, x: usize, y: usize) {
let root_x = find(parent, x);
let root_y = find(parent, y);
if root_x != root_y {
parent[[1]] = root_y;
}
}x or y directly instead of their roots.parent[root_y] instead of parent[root_x].To merge two sets, we set the parent of root_x to root_y. This connects the root of one set to the root of the other.
Fill both blanks to implement union by rank optimization.
fn union(parent: &mut Vec<usize>, rank: &mut Vec<usize>, x: usize, y: usize) {
let root_x = find(parent, x);
let root_y = find(parent, y);
if root_x != root_y {
if rank[root_x] < rank[[1]] {
parent[root_x] = [2];
} else if rank[root_y] < rank[root_x] {
parent[root_y] = root_x;
} else {
parent[root_y] = root_x;
rank[root_x] += 1;
}
}
}x or y instead of root variables.Union by rank attaches the smaller tree under the root of the larger tree. When rank[root_x] < rank[root_y], we set parent[root_x] = root_y.
Fill all three blanks to implement path compression and union by rank in find and union functions.
fn find(parent: &mut Vec<usize>, x: usize) -> usize {
if parent[x] != x {
parent[x] = [1];
}
parent[x]
}
fn union(parent: &mut Vec<usize>, rank: &mut Vec<usize>, x: usize, y: usize) {
let root_x = find(parent, x);
let root_y = find(parent, y);
if root_x != root_y {
if rank[root_x] < rank[root_y] {
parent[root_x] = [2];
} else if rank[root_y] < rank[root_x] {
parent[root_y] = root_x;
} else {
parent[root_y] = root_x;
rank[root_x] += [3];
}
}
}parent[x] in find.union.In find, path compression sets parent[x] to the root by recursively calling find. In union, union by rank attaches smaller rank tree under larger and increments rank by 1 when ranks are equal.
