Sign in

DSU with Live Component Count

core

Extend your DSU with a count() query that returns how many connected components currently exist. All n nodes start as singleton components, so count begins at n. unite(a, b) merges the components containing a and b, decreasing count by exactly one only when a and b were not already connected; a redundant union, including a self-union like U x x, must leave count unchanged.

Operations arrive as U a b (unite) or C (print count() on its own line).

Example: DSU dsu(5) starts at count() == 5. dsu.unite(0, 1) drops it to 4; dsu.unite(1, 2) drops it to 3. dsu.unite(0, 2) is redundant (0 and 2 are already connected through 1), so count() stays 3.

Input format: each test in tests/*.in is laid out as:

  • Line 1: n q, the element count and the number of operations; elements are numbered 0 to n - 1.
  • Next q lines: one operation each, either U a b (union) or C (print the current component count).

Test 04.in reads:

3 5
C
U 1 1
C
U 0 1
C

This is 3 elements and 5 operations: a count before any union (3), a self-union U 1 1 that changes nothing (3 again), then U 0 1 merges two components (2).

Where you'll use it:

✦ Solution & editorial unlock with the pass.

Loading...