Problem Description
There are n houses in a village. Each house can either have a well built directly in it with a given cost, or be connected to another house via pipes (with their own costs) to receive water. The goal is to supply water to all houses with minimum total cost. Note that a well in any house is equivalent to connecting that house to a virtual water source.
Key Insights
- Transform the problem by introducing a virtual node (node 0) where connecting house i to this node costs wells[i - 1].
- Build a graph where the edges are both the actual pipes between houses and edges from the virtual node to each house representing the well cost.
- Use a Minimum Spanning Tree (MST) approach (either Kruskal’s or Prim’s algorithm) to connect all houses with the minimum cost.
- The MST will automatically choose the cheaper option between building a well and laying a connecting pipe.
Space and Time Complexity
Time Complexity: O((n + p) log(n + p)), where n is the number of houses and p is the number of pipes (for sorting the edges in the MST algorithm). Space Complexity: O(n + p) to store the union-find data structures and the edge list.
Solution
We solve the problem by modeling it as an MST problem. First, we add a virtual node (0) to represent a water source. Then, we connect this node to each house i with an edge that has a cost equal to wells[i - 1]. Next, we add all the given pipe connections between houses to the graph. With this graph setup, the problem reduces to finding the minimum spanning tree that connects all nodes (including the virtual node). We can then use Kruskal’s algorithm with a union-find data structure to build this MST. The union-find data structure helps efficiently determine whether adding an edge will create a cycle, while sorting the edges ensures that we always add the smallest available edge that connects two components of the graph.