Lv.3graphgreedymstunion-find
Connect All Villages
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
There are n villages 0..n-1 and candidate two-way roads roads[i] = [a, b, c] costing c. Choose roads so that every
village can reach every other (possibly through others) and return the minimum total cost, or -1 if that is impossible.
Examples
| n | roads | result |
|---|---|---|
4 | [[0, 1, 1], [1, 2, 4], [0, 2, 3], [2, 3, 2], [1, 3, 5]] | 6 |
3 | [[0, 1, 2]] | -1 |
1 | [] | 0 |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(n: int, roads: int[][]) → long
Constraints
-
n,roads.length - , ; parallel roads and self-loops may appear. The total can exceed 32 bits.
Expected complexity
- Time
- O(M log M)
- Space
- O(N + M)
Examples
| n | roads | Expected |
|---|---|---|
4 | [[0,1,1],[1,2,4],[0,2,3],[2,3,2],[1,3,5]] | 6 |
3 | [[0,1,2]] | -1 |
1 | [] | 0 |
Hint
Hint
Minimum spanning tree. Kruskal: sort roads by cost and take a road only if union–find says its ends are not yet connected;
n - 1 roads means done, otherwise -1. Array-scan Prim is and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 248 ms | estimated |
| C++ (GCC, gnu++23) | 248 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 2498 ms | derived |
| Kotlin 2.4 (JVM) | 1496 ms | estimated |
| C# 14 (.NET 10) | 1496 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 10 | verdict only |
| performance | 60 | 4 | verdict only |