#K88747. Count the Connected Components in an Undirected Graph

    ID: 37377 Type: Default 1000ms 256MiB

Count the Connected Components in an Undirected Graph

Count the Connected Components in an Undirected Graph

You are given a simple undirected graph with n vertices numbered from 1 to n. The graph is represented by a series of edges. Each edge is specified by two integers u and v, meaning that there is an undirected edge connecting vertices u and v. The edge input is terminated by the pair 0 0, which should not be considered as an edge.

Your task is to calculate the number of connected components in the graph.

Note:

  • The graph is undirected.
  • The vertices are numbered starting from 1.
  • If there are no edges, each vertex is considered as a separate connected component.

The solution may involve graph traversal techniques such as Depth First Search (DFS) or Breadth First Search (BFS). Use LaTeX format for any formulas. For example, the number of connected components \( C \) in a graph \( G(V, E) \) is defined by the number of distinct sets in which each set is a maximal set of vertices such that every pair of vertices in the set is connected by a path.

inputFormat

The input is read from standard input and is formatted as follows:

  • The first line contains a single integer n (\(1 \le n \le 10^5\)), the number of vertices in the graph.
  • Each subsequent line contains two integers u and v representing an edge. The input terminates when the pair 0 0 is encountered. This pair should not be processed as an edge.

outputFormat

Print a single integer to the standard output representing the number of connected components in the graph.

## sample
6
1 2
2 3
4 5
0 0
3