Skip to the code
cf.
+50 XP

#474 Cables in Every Cheapest Network

hard

A network of n sites numbered 0 to n - 1 can be built from the possible cables cables[i] = [a, b, cost], which work both ways. There may be several different cheapest networks (sets of cables that connect every site at the lowest total cost).

Write essentialCables(n, cables) that returns, sorted ascending, the indexes of the cables that appear in every cheapest network: removing such a cable from the options would make the cheapest network more expensive, or impossible. The sites can always be connected using all the cables.

Example 1

Input: n = 4, cables = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,2,3]]
Output: [0,1]

The cheapest network costs 4. Without cable 0 or cable 1 it would cost 5. Cables 2 and 3 can replace each other.

Example 2

Input: n = 3, cables = [[0,1,1],[1,2,1],[0,2,1]]
Output: []

Any two of the three equal cables make a cheapest network, so none is in every one.

Constraints

  • 2 <= n <= 100
  • n - 1 <= cables.length <= 200
  • 1 <= cost <= 1000
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).