#228MediumGraphs· Minimum Spanning Tree with Kruskal
Cheapest Fiber Backbone
Input format
`n`: number of sites; `links`: array of `[a, b, cost]`.
Output format
An integer: the minimum total cost, or -1 if the sites cannot be connected.
Examples
Input: n = 4, links = [[0, 1, 3], [1, 2, 4], [0, 2, 1], [2, 3, 2], [0, 3, 9]]
Output: 6
Take the cables costing 1, 2 and 3 (0-2, 2-3, 0-1): all four sites are connected for 6. The 4-cost and 9-cost cables are never needed.
Input: n = 3, links = [[0, 1, 5]]
Output: -1
Site 2 has no cable option, so the network cannot be connected.
Input: n = 1, links = []
Output: 0
One site is trivially connected at no cost.
Constraints
- 1 <= n <= 10^5
- 0 <= links.length <= 2 * 10^5
- 0 <= a, b < n, a != b
- 0 <= cost <= 10^4
- Parallel routes between the same two sites are allowed.
- #minimum-spanning-tree
- #kruskal
- #union-find
- #graph
- #greedy