P16 · 2 seconds · 256 MB
Road Reparation
You have `n` cities numbered `0..n-1` and a list of undirected roads `edges`, each `[u, v, w]`. Return the minimum total weight of a set of roads that connects every city. If it is impossible, return `-1`. Parallel edges may exist; pick the useful ones. Self-loops may exist; ignore them.
function mstWeight(n, edges) → number
CONSTRAINTS
- 1 ≤ n ≤ 200
- 0 ≤ edges.length ≤ 1000
- 0 ≤ u, v < n
- 0 ≤ w ≤ 10⁶
Input: n = 4, edges = [[0,1,1],[1,2,2],[0,2,4],[2,3,3],[0,3,10]]
Output: 6
Roads of weight 1, 2, and 3.
Input: n = 3, edges = [[0,1,5]]
Output: -1
City 2 is isolated.
1
2
3
4
5
6
7
8
Arena judges JavaScript in a Web Worker (1s wall-clock, then TLE). Samples are public; submit runs hidden tests too. C++/Python is a later swarm package.