#C3598. Counting Connected Components in an Undirected Graph

    ID: 47042 Type: Default 1000ms 256MiB

Counting Connected Components in an Undirected Graph

Counting Connected Components in an Undirected Graph

You are given an undirected graph with \(n\) nodes and \(m\) edges. The nodes are labeled from 1 to \(n\). Each of the \(m\) edges connects two nodes. Your task is to count the number of connected components in the graph.

Input Format:

  • The first line contains two integers \(n\) and \(m\).
  • The next \(m\) lines each contain two integers \(u\) and \(v\), representing an undirected edge between node \(u\) and node \(v\).

Output Format:

  • Output a single integer that represents the number of connected components in the graph.

Note that self-loops or multiple edges between the same pair of nodes might be present, but they should be handled correctly. Use standard input/output for reading and writing data.

inputFormat

The input begins with a line containing two integers \(n\) (the number of nodes) and \(m\) (the number of edges). Each of the following \(m\) lines contains two integers \(u\) and \(v\) representing an edge between nodes \(u\) and \(v\).

Example:

6 5
1 2
2 3
1 3
4 5
5 6

outputFormat

Output a single integer which is the total number of connected components in the graph.

Example:

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