Road Reparation
You are given an integer n representing the number of cities numbered from 1 to n. You are also given a 2D integer array roads where roads[i] = [u, v, cost] represents a bidirectional road between city u and city v that requires cost to repair.
Your task is to repair a subset of the roads so that all n cities are connected (i.e., there is a path between any two cities). Return the minimum total cost to repair the roads. If it is impossible to connect all cities, return -1.
Example 1:
Input: n = 5, roads = [[1, 2, 3], [2, 3, 5], [2, 4, 2], [3, 4, 8], [5, 1, 7], [5, 4, 4]]
Output: 14
Explanation:
Repair roads [2, 4, 2], [1, 2, 3], [5, 4, 4], and [2, 3, 5]. Total cost = 2 + 3 + 4 + 5 = 14. All 5 cities are connected.
Example 2:
Input: n = 3, roads = [[1, 2, 5]]
Output: -1
Explanation:
City 3 has no roads connecting it to the rest of the network, making it impossible.
Now Your Turn!
Pick the correct output for the given inputInput: n = 4, roads = [[1, 2, 1], [2, 3, 2], [3, 4, 3], [1, 4, 10]]
Still unsure what the problem is asking ?
Letās go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= n <= 105
- 1 <= roads.length <= 2 x 105
- roads[i].length == 3
- 1 <= roads[i][0], roads[i][1] <= n
- 1 <= roads[i][2] <= 109
- Every road is between two different cities, and there is at most one road between any two cities.