Ctrl K

Cheapest Links Into the Hub

Medium
A network has servers servers numbered 0 to servers - 1. Server 0 is the hub. Links are one-way: links[i] = [a, b, c] is a link from server a to server b that costs c. You may switch off some links (or none at all). Afterwards: - every server must be able to send data to server 0, possibly through other servers; - every server keeps at most limit outgoing links; - the cost of the most expensive remaining link should be as small as possible. Return that smallest possible cost of the most expensive link. If the conditions cannot be met, return -1.
Example 1
servers=4, links=[[1, 0, 3], [2, 1, 2], [3, 2, 5], [3, 0, 4]], limit=1 → 4

Keep 1 → 0, 2 → 1 and 3 → 0: every server reaches server 0 and the priciest link costs 4. Without a link costing 4 or 5, server 3 is cut off.

Example 2
servers=3, links=[[0, 1, 1], [1, 2, 1]], limit=1 → -1

The links only lead away from server 0, so servers 1 and 2 can never send it anything: the answer is -1.

Example 3
servers=3, links=[[1, 0, 7], [2, 0, 9], [2, 1, 1]], limit=2 → 7

Server 2 can route through server 1 (2 → 1 → 0), so the link costing 9 is not needed and the maximum is 7.

Constraints
  • 2 ≤ servers ≤ 10⁵
  • 1 ≤ limit ≤ servers - 1
  • 1 ≤ len(links) ≤ min(10⁵, servers · (servers - 1) / 2)
  • links[i] = [a, b, c], 0 ≤ a, b < servers, a ≠ b
  • 1 ≤ c ≤ 10⁶
  • Two servers may be joined by several links, but their costs differ
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRatio Chain Queries MediumShortest Path of a Rolling Ball MediumBroadcast Reach Time MediumCheapest Trip With Few Layovers MediumBall Into the Hole Hard
loading Python…
Input
servers=4, links=[[1, 0, 3], [2, 1, 2], [3, 2, 5], [3, 0, 4]], limit=1
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 86 tests on the server, hidden ones included.