A telecom company wants to lay cables between n hubs, numbered 0 to n - 1, so that
every hub can communicate with every other hub (directly or through other hubs). There are m
candidate two-way cable routes; route i connects hubs u and v at a build cost of w. Multiple
candidate routes between the same pair of hubs may be offered, at different costs.
Print the minimum total cost of a set of cables that connects all n hubs into a single network. If
it is impossible to connect all hubs no matter which cables are chosen, print -1 instead.
Line 1: two integers n m.
Next m lines: three integers u v w -- an undirected candidate cable between hubs u and v
costing w to build (hubs are 0-indexed).
A single integer: the minimum total build cost to connect all hubs, or -1 if it is impossible.
Example 1
Input
4 5 0 1 1 1 2 2 2 3 3 0 3 10 0 2 4
Expected
6
Explanation
The cheapest way to link all four hubs is the chain 0-1-2-3 using cables of cost 1, 2 and 3, for a total build cost of 6; the pricier 0-3 and 0-2 cables are not needed.
Example 2
Input
3 1 0 1 5
Expected
-1
Explanation
Hub 2 has no cable linking it to the rest of the network, so all hubs can never be connected, giving -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →