Skip to the code
cf.
+10 XP

#471 Connect the Office Buildings

easy

A campus has n buildings numbered 0 to n - 1. Each options[i] = [a, b, cost] is a possible fiber link between buildings a and b and what it would cost. Links work both ways.

Write cheapestNetwork(n, options) that returns the smallest total cost of links that connects every building, or -1 if it's impossible.

Example 1

Input: n = 4, options = [[0,1,1],[1,2,2],[0,2,4],[2,3,3],[1,3,5]]
Output: 6

Links 0-1, 1-2, and 2-3 cost 1 + 2 + 3 = 6 and connect everything.

Example 2

Input: n = 3, options = [[0,1,5]]
Output: -1

Building 2 has no possible link.

Constraints

  • 1 <= n <= 10000
  • 0 <= options.length <= 50000
  • 1 <= cost <= 10^5
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).