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
Time & Space Complexity
Sorting (m+n) edges takes O((m+n) log(m+n)), Union-Find operations are nearly O(1) with path compression
Space for storing edges, Union-Find parent array, and rank array
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]