A network has n devices labeled 1 through n. Initially every device is isolated. You then apply m merge operations one at a time; each operation names two devices and places them (and everything already grouped with either of them) into the same group. A device may be merged with itself, and the same pair may be merged more than once — such operations simply have no effect. After all merges, report how many distinct groups (connected components) remain.
n and m — the number of devices and the number of merge operations.m lines: each contains two integers u and v (1-indexed) — merge the groups containing u and v.A single integer: the number of connected components after all merges.
Example 1
Input
6 3 1 2 2 3 5 6
Expected
3
Explanation
Merges 1-2 and 2-3 fuse {1,2,3}. Merge 5-6 fuses {5,6}. Device 4 stays alone. Groups: {1,2,3}, {4}, {5,6} → 3 components.
Example 2
Input
4 3 1 1 2 3 2 3
Expected
3
Explanation
Merge 1-1 is a self-merge (no effect). Merges 2-3 and 2-3 fuse {2,3} (the second is a repeat). Groups: {1}, {2,3}, {4} → 3 components.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →