AmazonOA #117
Count Connected Components
Estimated MediumJudge-ready
Topics (AI-labelled)Union-Find
Given an undirected graph with nodes numbered 0..n−1, find the number of connected components. Duplicate edges and self-loops do not change connectivity, and an isolated node also counts as a component.
Input
The first line contains n m; each of the next m lines contains u v. This site sets 1≤n≤200000, 0≤m≤200000, 0≤u,v<n.
Output
Output a single integer answer.
Example 1
Input:
5 3
0 1
1 2
3 4
Output:
2
Example 2
Input:
4 0
Output:
4
Example 3
Input:
3 3
0 0
0 1
0 1
Output:
2
Example notes
Example 1: {0,1,2} and {3,4}, 2 groups in total. Example 2: all four nodes are isolated, so the answer is 4. Example 3: 0 and 1 are connected and 2 is isolated; the self-loop and the duplicate edge do not reduce the component count further, so the answer is 2.
Editorial
Loading solution…