#C9160. Minimum Distance to Connect All Parts
Minimum Distance to Connect All Parts
Minimum Distance to Connect All Parts
You are given an undirected weighted graph with \(n\) nodes and \(m\) edges. Your task is to determine the minimum total distance needed to connect all nodes using the edges provided. This is equivalent to finding the Minimum Spanning Tree (MST) of the graph.
If a spanning tree exists, output the sum of the weights of its edges. Otherwise, print impossible
. Note that if \(n = 1\), the answer is \(0\).
You may use Kruskal's algorithm using Union-Find to efficiently solve this problem. The key requirement is that the input graph must have exactly \(n-1\) edges in the resulting tree if it is connected.
inputFormat
The first line contains two space-separated integers \(n\) and \(m\), where \(n\) is the number of nodes and \(m\) is the number of edges. Each of the following \(m\) lines contains three space-separated integers \(u\), \(v\), and \(w\) representing an edge between nodes \(u\) and \(v\) with weight \(w\).
outputFormat
Output a single line. If it is possible to connect all nodes, output the minimum total weight of the spanning tree; otherwise, output impossible
.
4 5
1 2 2
1 3 3
1 4 1
2 3 4
3 4 5
6
</p>