#K33392. Minimum Energy Cost for Planetary Connectivity
Minimum Energy Cost for Planetary Connectivity
Minimum Energy Cost for Planetary Connectivity
You are given a network of planets and a list of available energy channels between them. Each channel connects two different planets with a given energy cost. Your task is to compute the minimum total energy cost required to connect all planets. This problem is equivalent to finding the Minimum Spanning Tree (MST) of a graph.
Formally, you are given an integer \(T\) representing the number of test cases. For each test case, you are provided with two integers \(N\) and \(M\), where \(N\) is the number of planets and \(M\) is the number of channels. Each of the following \(M\) lines contains three integers \(u\), \(v\), and \(w\), where \(u\) and \(v\) denote the endpoints (planets) and \(w\) is the energy cost to use that channel. You need to calculate the minimum cost to connect all planets using these channels. If there are no channels and only one planet exists, the cost is zero.
The MST can be efficiently determined using Kruskal's algorithm or Prim's algorithm, but in this problem, you should implement the solution using Kruskal's algorithm with a union-find data structure.
inputFormat
The input is read from stdin
and has the following format:
T N1 M1 u1 v1 w1 u2 v2 w2 ... (M1 lines) N2 M2 ... (M2 lines) ... NT MT ... (MT lines)
Where:
- T is the number of test cases.
- For each test case, the first line contains two space-separated integers: N (the number of planets) and M (the number of energy channels).
- Each of the next M lines for that test case contains three space-separated integers \(u\), \(v\), and \(w\), representing a channel between planet u and planet v with cost w.
outputFormat
For each test case, print a single integer on a new line representing the minimum total energy cost required to connect all the planets.
The output is written to stdout
.
2
4 5
1 2 3
2 3 4
3 4 5
4 1 6
1 3 2
3 3
1 2 1
2 3 2
3 1 3
10
3
</p>