##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
5 2 3 1 2 3 4 2 3 5 1 4 10 4 5 3
8
3 2 1 1 2 2 3 1 3 7
0
4 1 1 1 2 1 2 5
-1
Given nodes and existing bidirectional edges (which are free to use), plus a list of possible new edges each with an associated cost, find the minimum total cost to make all nodes connected (i.e., form a single connected component).
If the nodes are already connected using only existing edges, output . If it is impossible to connect all nodes even after using all available new edges, output .
There are 5 nodes. Existing edges connect and , and node 5 is isolated. We need to connect all three components. The cheapest new edge is with cost 3, merging node 5 into . Next cheapest is with cost 5, merging the two large components. Total cost: 8.
All 3 nodes are already connected via existing edges: and . No new edges are needed. Answer: 0.
Nodes are connected by the existing edge. Nodes 3 and 4 are isolated. The only available new edge connects 1 and 2 again, which does not help. It is impossible to connect all nodes. Answer: -1.