#K471. Minimum Channels to Connect Wells

    ID: 28123 Type: Default 1000ms 256MiB

Minimum Channels to Connect Wells

Minimum Channels to Connect Wells

You are given a set of wells and a list of channels connecting some of these wells. Your task is to determine the minimum number of additional channels required so that every well is reachable from any other well.

Formally, there are N wells labeled from 1 to N and M channels. Each channel connects two distinct wells in an undirected manner. The graph formed by the wells and channels might be disconnected. In such a case, you need to add the minimum number of extra channels to connect all the components. If the graph is already connected, no additional channel is needed.

The answer is \(\max(0, C - 1)\), where \(C\) is the number of connected components in the undirected graph.

inputFormat

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

  1. An integer N, the number of wells.
  2. An integer M, the number of channels.
  3. M lines follow, each containing two space-separated integers u and v representing a channel between wells u and v.

outputFormat

Output a single integer representing the minimum number of channels that need to be added so that all wells are connected.

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

</p>