Data Structures & AlgorithmsHardGATE CS · ICPC regional
Elements 0 to 5 start as singletons. For each call union(a, b), in order: let ra and rb be the roots of a and b. If ra = rb nothing happens. Otherwise the root of the smaller set is attached below the root of the larger set, and when the two sets have equal size the root ra (of the first argument) stays the root. The calls are union(0, 4), union(4, 4), union(3, 1), union(0, 0), union(4, 4), union(4, 4), union(3, 0), union(0, 2), union(0, 3). Which element is the root of the set containing 4 after all calls?
- A. 3
- B. 4
- C. 0
- D. 2
Correct answer: A. 3
Union by size keeps the root of the larger tree; the tie rule decides the root only when sizes are equal. Attaching the first argument's root under the second, or using the smaller index as root, gives a different root.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Elements 0 to 5 start as singletons. For each call union(a, b), in order: let ra and rb be the roots of a and b. If ra = rb nothing…
- Elements 0 to 9 start as singletons. For each call union(a, b), in order: let ra and rb be the roots of a and b. If ra = rb nothing…
- Elements 0 to 6 start as singletons. For each call union(a, b), in order: let ra and rb be the roots of a and b. If ra = rb nothing…
- Elements 0 to 5 start as singletons. For each call union(a, b), in order: let ra and rb be the roots of a and b. If ra = rb nothing…
- Elements 0 to 8 start as singletons. For each call union(a, b), in order: let ra and rb be the roots of a and b. If ra = rb nothing…
- Elements 0 to 7 start as singletons. For each call union(a, b), in order: let ra and rb be the roots of a and b. If ra = rb nothing…