#K53447. Minimum New Connections
Minimum New Connections
Minimum New Connections
You are given a system consisting of N servers and M bidirectional connections between them. Each connection links two servers and is associated with a length, although the length does not affect connectivity. Your task is to determine the minimum number of new connections required to make the entire system fully connected. In other words, you need to count the number of disconnected components and output the number of additional connections needed (which is one less than the number of disconnected components).
The problem can be solved using a union-find (disjoint set union) data structure to efficiently merge connected components and count the number of separate groups. Formally, if the system initially has C connected components, then the answer is C - 1 since each new connection can merge two components.
inputFormat
The input is read from standard input (stdin) and has the following format:
T N1 M1 X11 Y11 L11 X12 Y12 L12 ... X1M1 Y1M1 L1M1 N2 M2 ... NT MT ...
Here, T is the number of test cases. For each test case, the first line contains two integers N (the number of servers) and M (the number of existing connections). Each of the next M lines contains three integers X, Y, and L which represent a connection between servers X and Y with a given length L (the length is informational only).
outputFormat
For each test case, output a single integer on its own line representing the minimum number of new connections required to fully connect the network of servers. The output should be written to standard output (stdout).
## sample2
5 3
1 2 1
2 3 2
4 5 3
4 5
1 2 1
1 3 2
3 4 1
1
0
</p>