Ctrl K

Water for the Whole Village

Hard
A village has house_count houses numbered 1 to house_count, and every one of them needs water. There are two ways to get it: - dig a well right in house i, which costs well_cost[i - 1]; - run a pipe from a house that already has water. The entry pipes[j] = [a, b, cost] says houses a and b can be linked with a pipe for cost; water flows both ways. The same pair of houses may appear several times with different prices. Return the lowest total cost that gets water into every house.
Example 1
house_count=3, well_cost=[5, 1, 4], pipes=[[1, 2, 2], [2, 3, 6]] → 7

A well in house 2 for 1 and a pipe 1–2 for 2. For house 3 its own well (4) is cheaper than the pipe (6). Total 1 + 2 + 4 = 7.

Example 2
house_count=2, well_cost=[0, 0], pipes=[[1, 2, 3]] → 0

Wells are free, so no pipes are needed.

Example 3
house_count=4, well_cost=[9, 9, 2, 9], pipes=[[1, 2, 1], [2, 3, 3], [3, 4, 1], [1, 4, 5]] → 7
Constraints
  • 2 ≤ house_count ≤ 10⁴
  • len(well_cost) = house_count
  • 0 ≤ well_cost[i] ≤ 10⁵
  • 1 ≤ len(pipes) ≤ 10⁴
  • 1 ≤ a, b ≤ house_count, a ≠ b
  • 0 ≤ cost ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThe Cheapest Road Network MediumRequired and Spare Cables HardCheapest Point Wiring MediumBall Into the Hole HardThe Extra Link in a Rooted Tree Hard
loading Python…
Input
house_count=3, well_cost=[5, 1, 4], pipes=[[1, 2, 2], [2, 3, 6]]
Expected
7

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