Here is the algorithm:
Sort edges by weight
Run Kruskal with Union-Find
Count edges added to MST
If count equals , return total weight
Otherwise, return "IMPOSSIBLE" The validation is a single comparison at the end.
The hard part is implementing Union-Find correctly. Make sure to use path compression and union by rank for speed. Without these techniques, Union-Find becomes slow and you will time out on large inputs.