Optimize Water Distribution in a Village - Problem
There are n houses in a village. We want to supply water for all the houses by building wells and laying pipes.
For each house i, we can either build a well inside it directly with cost wells[i - 1] (note the -1 due to 0-indexing), or pipe in water from another well to it.
The costs to lay pipes between houses are given by the array pipes where each pipes[j] = [house1j, house2j, costj] represents the cost to connect house1j and house2j together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs.
Return the minimum total cost to supply water to all houses.
Input & Output
Example 1 — Basic Water Distribution
$
Input:
n = 3, wells = [1,2,1], pipes = [[1,2,1],[2,3,1]]
›
Output:
3
💡 Note:
Build wells in houses 1 and 3 (cost 1+1=2), then connect house 2 to house 3 via pipe (cost 1). Total: 2+1=3.
Example 2 — All Wells Cheaper
$
Input:
n = 2, wells = [1,1], pipes = [[1,2,2]]
›
Output:
2
💡 Note:
Building wells in both houses costs 1+1=2, which is cheaper than one well plus pipe (1+2=3).
Example 3 — Pipes More Efficient
$
Input:
n = 4, wells = [3,3,3,3], pipes = [[1,2,1],[1,3,1],[1,4,1]]
›
Output:
6
💡 Note:
Build one well in house 1 (cost 3) and connect others via pipes (cost 1+1+1=3). Total: 6.
Constraints
- 1 ≤ n ≤ 104
- wells.length == n
- 0 ≤ wells[i] ≤ 105
- 1 ≤ pipes.length ≤ 3 × 104
- pipes[j].length == 3
- 1 ≤ house1j, house2j ≤ n
- 0 ≤ costj ≤ 105
- house1j ≠ house2j
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code