Spread a new build across regions at least cost

Agent buildHard40 min

Your task

You are rolling a new build of your agent out to your regions, and only region 0 has it so far. A region gets the build by copying it over a one-way link, and each link has its own transfer cost, which often differs by direction.

Write cheapest_spread(n, links) that returns the lowest total cost of getting the build to every region.

Input and output:

  • n: the number of regions, a whole number from 1 to 300. Regions are numbered 0 to n - 1.
  • links: 0 to 3,000 links, each [a, b, cost], in any order. The build can be copied from region a to region b. a and b are different. cost is a whole number from 0 to 1,000,000,000. The same pair may appear more than once, with any costs.
  • Return a whole number, or -1 if some region cannot get the build at all.

Rules:

  • A plan is a set of links. It works when every region can be reached from region 0 by following links in the set, in their direction.
  • A plan's cost is the sum of the costs of its links. Each link is paid once, however many regions the build reaches through it.
  • With one region, nothing needs copying, so the cost is 0.

Examples

cheapest_spread(n: int, links: list[list[int]]) -> int
Example 1
Inputcheapest_spread(3, [[0, 1, 10], [1, 2, 1], [2, 1, 1], [0, 2, 8]])
Output9
Example 2
Inputcheapest_spread(4, [[0, 1, 5], [1, 2, 5], [2, 3, 5], [3, 1, 1], [0, 3, 7]])
Output13
Example 3
Inputcheapest_spread(3, [[1, 2, 4], [2, 1, 4]])
Output-1