Advanced graphs and trees · 11 / 15 Exercise Hard

Merging groups

Objective

The union-find structure keeps disjoint groups: each element points to a “parent” and the root identifies the group. Merging two groups and knowing whether two elements are together are almost instantaneous operations.

Instructions

  • The first line has n m (elements, from 0 to n-1, and number of unions); then m lines a b, each merging the group of a with that of b.
  • After each union show, on its own line, how many distinct groups remain (at the start there are n).
Input
5 4
0 1
2 3
1 3
0 3
Output
4
3
2
2

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise