Optimize Water Distribution in a Village - Problem
You are tasked with designing an optimal water distribution system for a village with n houses. To ensure every house has access to water, you have two options for each house:
- Build a well directly inside the house at cost
wells[i-1]for housei - Connect to another well via pipes with costs specified in the
pipesarray
The pipes array contains entries [house1, house2, cost] representing the cost to connect two houses bidirectionally. Multiple connections between the same houses are possible with different costs.
Goal: Find the minimum total cost to supply water to all houses in the village.
This is a classic Minimum Spanning Tree problem with a twist - we can add virtual wells!
Input & Output
example_1.py — Basic village with 3 houses
$
Input:
n = 3, wells = [1, 2, 2], pipes = [[1, 2, 1], [2, 3, 1]]
›
Output:
3
💡 Note:
Optimal: Build well at house 1 (cost 1), connect house 2 to house 1 via pipe (cost 1), connect house 3 to house 2 via pipe (cost 1). Total cost = 1 + 1 + 1 = 3.
example_2.py — Expensive pipes scenario
$
Input:
n = 2, wells = [1, 1], pipes = [[1, 2, 2]]
›
Output:
2
💡 Note:
Building wells in both houses costs 1 + 1 = 2, while connecting via pipe would cost min(1) + 2 = 3. Better to build individual wells.
example_3.py — Large village optimization
$
Input:
n = 4, wells = [3, 3, 3, 4], pipes = [[1, 2, 2], [1, 3, 2], [2, 4, 2]]
›
Output:
7
💡 Note:
Build well at house 1 (cost 3), connect houses 2, 3, 4 via minimum cost pipes: 1-2 (cost 2), 1-3 (cost 2). Total = 3 + 2 + 2 = 7.
Constraints
- 1 ≤ n ≤ 104
- wells.length == n
- 0 ≤ pipes.length ≤ 3 × 104
- pipes[j].length == 3
- 1 ≤ wells[i] ≤ 105
- 1 ≤ pipes[j][0], pipes[j][1] ≤ n
- 0 ≤ pipes[j][2] ≤ 105
- pipes[j][0] ≠ pipes[j][1]
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code