#C3303. Connect Landmarks with Minimum New Roads
Connect Landmarks with Minimum New Roads
Connect Landmarks with Minimum New Roads
You are given several datasets representing a collection of landmarks and some existing roads connecting them. Each dataset describes an undirected graph where the nodes represent landmarks and the edges represent roads connecting these landmarks.
Your task is to determine the minimum number of new roads required to connect all the landmarks in each dataset. In other words, you must calculate the number of additional edges needed so that the graph becomes connected.
If a graph has k connected components, then the minimum number of new roads required is given by:
$$ answer = k - 1 $$
Note that if the graph is already connected (i.e. k = 1), then no new road is needed (answer is 0).
Input and Output are taken from standard input and written to standard output respectively.
inputFormat
The input will begin with a single integer T
on the first line, indicating the number of test cases.
Each test case is described as follows:
- The first line of a test case contains two integers
V
andE
separated by a space, whereV
represents the number of landmarks (numbered from 1 to V), andE
indicates the number of existing roads. - This is followed by
E
lines, each containing two integersu
andv
separated by a space, representing an undirected road between landmarksu
andv
.
You should read from standard input.
outputFormat
For each test case, output a single integer on its own line representing the minimum number of new roads required to connect all the landmarks.
Write your output to standard output.
## sample2
5 2
1 2
3 4
3 3
1 2
2 3
3 1
2
0
</p>