cswork / OA打开练习工作台

AmazonOA #117

Count Connected Components

估计中等可在线判题

考点(AI 标注)并查集

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.

输入格式

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 a single integer answer.

样例 1

输入:

5 3
0 1
1 2
3 4

输出:

2

样例 2

输入:

4 0

输出:

4

样例 3

输入:

3 3
0 0
0 1
0 1

输出:

2

样例说明

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.