Problem 161
Connected Components
Medium · 20 pts · Graph, Depth-First Search, Union Find
Problem
You are given an undirected graph with N nodes labelled 1 to N and M edges. A connected component is a group of nodes in which every node can reach every other node through edges, and no node outside the group can be reached. Count the connected components. A node with no edges forms a component on its own. Run a BFS or DFS from every node that has not been visited yet; each such start discovers one new component. A union-find (disjoint set) structure that merges the two ends of every edge works as well.
Input
First line: integers N (nodes, labelled 1..N) and M (edges). Next M lines: an edge u v.
Output
Print the number of connected components.
Constraints
1 <= N <= 100000; 0 <= M <= 200000
Example input
5 3 1 2 2 3 4 5
Example output
2
Explanation
The edges 1-2 and 2-3 join nodes 1, 2 and 3 into one component, and the edge 4-5 joins nodes 4 and 5 into another. So there are 2 components.