Optimize Water Distribution in a Village

Min cost to supply water to all houses — MST with a virtual well source.

Hard
Time O(E log E) Space O(N + E)
LeetCode
6 min read
union-find mst kruskal graph

Problem#

There are n houses. House i can have its own well (cost wells[i-1]) or share water via pipes (each pipe [a, b, cost]). Return the minimum total cost to bring water to every house.

Examples#

  • n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]]3 (well at 1 cost 1, pipes 1-2 and 2-3 cost 1 each).
  • n = 2, wells = [1,1], pipes = [[1,2,1],[1,2,8]]2.

Constraints#

  • 2 <= n <= 10^4, 0 <= pipes.length <= 10^4.

Hints#

Hint
Model each well as a pipe from a virtual node 0 to the house with cost wells[i]. Then MST over n + 1 nodes.

Approach#

Add virtual node 0. For each house i create edge (0, i, wells[i-1]). Combine with the given pipes. Kruskal’s MST over n + 1 nodes — sum of accepted edge costs is the answer.

Solution#

Optimize Water Distribution in a Village
class Solution {
vector<int> parent, rnk;
int find(int x) { while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }
bool unite(int a, int b) {
a = find(a); b = find(b); if (a == b) return false;
if (rnk[a] < rnk[b]) swap(a, b);
parent[b] = a; if (rnk[a] == rnk[b]) ++rnk[a];
return true;
}
public:
int minCostToSupplyWater(int n, vector<int>& wells, vector<vector<int>>& pipes) {
vector<tuple<int,int,int>> edges;
for (int i = 0; i < n; ++i) edges.emplace_back(wells[i], 0, i + 1);
for (auto& p : pipes) edges.emplace_back(p[2], p[0], p[1]);
sort(edges.begin(), edges.end());
parent.resize(n + 1); rnk.assign(n + 1, 0);
iota(parent.begin(), parent.end(), 0);
int total = 0, used = 0;
for (auto& [w, a, b] : edges) {
if (unite(a, b)) { total += w; if (++used == n) break; }
}
return total;
}
};

Editorial#

The virtual-node trick converts the asymmetry between “build well” and “lay pipe” into a uniform MST problem. With n + 1 nodes (houses plus the virtual source), MST has exactly n edges — every house either connects to the source (well) or to another house (pipe). Kruskal’s runs in O(E log E).

Complexity#

  • Time: O((N + P) log (N + P)).
  • Space: O(N + P).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.