A campus has n buildings, numbered 0 to n - 1. Some pairs of buildings already have a
free, existing network trunk between them (m1 such pairs). In addition, there are m2 candidate
priced links that could be built; candidate link i connects buildings u and v at a cost of w.
Choose a subset of the candidate links (in addition to all of the free existing trunks) so that every
building ends up connected to every other building, directly or indirectly. Print the minimum total
cost of the candidate links you must buy to achieve this. If it is impossible to connect all buildings
even using every candidate link, print -1 instead.
Line 1: three integers n m1 m2.
Next m1 lines: two integers u v -- an existing free trunk between buildings u and v.
Next m2 lines: three integers u v w -- a candidate link between buildings u and v costing w
to build.
All buildings are 0-indexed; all links are undirected.
A single integer: the minimum total cost of candidate links needed to connect every building, or -1
if it cannot be done.
Example 1
Input
4 1 3 0 1 1 2 5 2 3 1 0 3 10
Expected
6
Explanation
Buildings 0 and 1 are already linked for free. Buying candidate link 2-3 (cost 1) and then 1-2 (cost 5) connects everything for a total spend of 6; the pricier 0-3 link is unnecessary.
Example 2
Input
3 0 1 0 1 4
Expected
-1
Explanation
No candidate link ever touches building 2, so it can never be wired into the network no matter which candidates are bought, 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 →