Problem 587770 · easy · Phase 05 Advanced Algorithms & Graphs

Cheapest Cable Layout

graphs · minimum spanning tree · Kruskal · union-find

A campus has n buildings labelled 0 .. n-1. Engineers have priced a list of possible fibre cables: cables[i] = [u, v, cost] would join buildings u and v (undirected) for cost. Two buildings may have several quotes.

Choose cables so that every building can reach every other one (directly or through other buildings) and the total cost is as small as possible. Return that total, or -1 if no choice of cables connects everything. A single building needs no cable, so the answer is 0.

Examples

Input:  n = 4, cables = [[0,1,3],[1,2,1],[2,3,4],[0,2,2],[1,3,5]]
Output: 7
Explanation: take 1-2 (1), 0-2 (2) and 2-3 (4). Cable 0-1 would only close a loop.

Input:  n = 3, cables = [[0,1,2]]
Output: -1
Explanation: building 2 has no cable at all.

Constraints

  • 1 <= n <= 10**4, 0 <= len(cables) <= 2 * 10**4, 0 <= cost <= 10**6
  • Target O(E log E) time.

Goals

  • Sort candidate edges by cost and add them greedily
  • Use union-find to reject edges that would close a loop
  • Detect when the buildings cannot all be connected
Starting Python…