#K89162. Minimum Repair Cost in the Kingdom of Avalon
Minimum Repair Cost in the Kingdom of Avalon
Minimum Repair Cost in the Kingdom of Avalon
You are given a kingdom with n castles and m roads. Each road connects two distinct castles and has an associated repair cost. The task is to determine the minimum total repair cost required to connect all the castles so that there is a path between any two castles. If it is impossible to connect all the castles, output IMPOSSIBLE.
This problem can be modeled using a graph, where castles are vertices and roads are edges with weights. The solution involves finding the Minimum Spanning Tree (MST) of the graph. In mathematical terms, if we denote the set of selected edges as E', then we need to find:
$$\min \sum_{e \in E'} w(e)$$
subject to the condition that the graph formed by E' is connected and spans all n vertices.
If a MST does not exist because the graph is disconnected, the answer should be the string IMPOSSIBLE
.
inputFormat
The first line of input contains two integers n
and m
, where:
n
(1 ≤ n ≤ 10^5) is the number of castles.m
(0 ≤ m ≤ 10^5) is the number of roads.
The following m
lines each contain three integers u
, v
and w
(1 ≤ u, v ≤ n, 1 ≤ w ≤ 10^9), representing a road connecting castle u
and castle v
with repair cost w
.
outputFormat
If it is possible to connect all the castles, output a single integer representing the minimum total repair cost required. Otherwise, output the string IMPOSSIBLE
.
4 4
1 2 3
2 3 4
3 4 5
4 1 6
12