#K70882. Connected Components in an Undirected Graph

    ID: 33407 Type: Default 1000ms 256MiB

Connected Components in an Undirected Graph

Connected Components in an Undirected Graph

You are given an undirected graph with \(n\) vertices and \(m\) edges. The vertices are numbered from 1 to \(n\). Your task is to determine the number of connected components in the graph.

A connected component is a set of vertices in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the graph. Formally, given an undirected graph \(G=(V,E)\) where \(|V|=n\) and \(|E|=m\), find the number of connected components.

Input: The input is read from standard input. The first line contains two integers \(n\) and \(m\) (\(1 \le n \le 10^5\), \(0 \le m \le 10^5\)), representing the number of vertices and edges respectively. The following \(m\) lines each contain two integers \(u\) and \(v\) (\(1 \le u,v \le n\)), indicating that there is an undirected edge between vertices \(u\) and \(v\).

Output: Output a single integer representing the number of connected components in the graph.

inputFormat

The input is provided via standard input. The first line contains two integers \(n\) and \(m\). Each of the next \(m\) lines contains two integers \(u\) and \(v\), representing an edge between vertices \(u\) and \(v\).

Example:
5 3
1 2
2 3
4 5

outputFormat

Output a single integer representing the number of connected components.

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