1168. Optimize Water Distribution in a Village #365
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Resolves: #211
Before talking about this problem, it's best to review previous problems on Union-Find:
#332, Union-Find Solution
#329
#200
These two problems also provide us great templates for efficient directed/undirected graph creation:
#330
#332, DFS Solution
Algorithm:
What does it mean to have a well here? A well from a house is just a weighted edge to some water-source vertex, a weighted edge like all pipes between the houses, which are also vertices.

What we should do is then connect all these vertices, the water source and the houses, with minimum cost. This is nearly the exact same problem we had in #24. We have to find the minimum spanning tree (MST) for this graph of wells as edges from a water source and houses with pipes.
There are two ways of doing this:
Approach 1-Union-Find/Kruskal
A visualization of this from Wikipedia
This classical Union-Find approach begins by adding all edges of this graph to a priority queue (using sorting is also possible). We poll the shortest edge from it each time. If the root of two vertices of this edge are equal, they are already connected and we don't need to connect them again. Else, we connect them and assign parents using the rank system. We add the edge's cost to the total and decrement the number of unconnected components until we are left with 1, when we have "connected" all the vertices.
Approach 2-Prim's Algorithm
A visualization of this from Wikipedia
Instead of picking the smallest edge from the entire graph, we can begin with some node (preferably the water source) and add nodes to this tree by selecting the shortest edge connected to this tree. If we add some node
ato the tree, we also add all of its unvisited nodes to the priority queue to visit them. When the number of elements in the tree equal to n (we don't count the water source) that means that all houses are connected and we can return the costs.