#K5971. Minimum Additional Connections
Minimum Additional Connections
Minimum Additional Connections
You are given a network of n nodes (numbered from 1 to n) and m bidirectional connections (friendships). Your task is to determine the minimum number of additional connections required to connect the network completely so that there is a path between any two nodes.
In other words, if the network is divided into several connected components, you need to add edges to connect these components. Note that, mathematically, if the number of connected components is \(C\), then you need to add exactly \(C-1\) connections to make the network fully connected.
Input/Output via Standard Input/Output
inputFormat
The first line contains an integer T representing the number of test cases. Each test case begins with a line containing two integers n and m, representing the number of nodes and the number of existing connections, respectively.
This is followed by m lines, each containing two integers u and v (with 1 ≤ u, v ≤ n), denoting that there is an existing connection between node u and node v.
outputFormat
For each test case, output a single integer on a new line, representing the minimum number of additional connections required to connect all the nodes.
## sample5
5 3
1 2
1 3
4 5
3 2
1 2
2 3
4 0
4 1
1 2
4 4
1 2
2 3
3 4
4 1
1
0
3
2
0
</p>