Funcia
Lv.3graphgreedymstunion-find

Connect All Villages

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
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

nroadsresult
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

  • 1≤1 \le n ≤100,000\le 100{,}000, 0≤0 \le roads.length ≤200,000\le 200{,}000
  • 0≤a,b<n0 \le a, b < n, 1≤c≤1061 \le c \le 10^6; 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

nroadsExpected
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 O(N2)O(N^2) and exceeds the time limit.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)248 msestimated
C++ (GCC, gnu++23)248 msderived
Python 3.131000 msderived
Java 252498 msderived
Kotlin 2.4 (JVM)1496 msestimated
C# 14 (.NET 10)1496 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4010verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.