Search⌘ K
AI Features

Solution: Optimize Water Distribution in a Village

Explore how to efficiently optimize water supply in a village by applying the Union-Find algorithm to connect houses via wells or pipes. Understand the problem as a graph connectivity challenge and learn to implement a minimal cost solution by treating wells and pipes as edges. This lesson guides you through sorting edges, performing union operations, and calculating the minimal total cost to ensure water access for every house using a structured approach.

Statement

There are nn houses in a village, and we want to supply water to every house. To do this, we have two options:

  1. Build a well directly at a house: The costs for building wells are given in the wells array, where wells[i - 1] represents the cost to build a well at house i (houses are numbered from 11 to nn, but the array is 0-indexed).

  2. Lay water pipes to connect two houses: Allowing one to receive water from the other. The costs for building these connections are given in the pipes array. Each pipe entry is written as [house1, house2, cost], meaning it costs to construct a pipe connecting house1 and house2. The connection is two-way (water can flow in both directions).

In the given data, multiple pipe entries may connect the same pair of houses, but with different costs. Each entry represents an available option; you may choose the most cost-effective one.

Your task is to determine the minimum total cost to ensure every house gets access to water, either by building a well directly at it or connecting it via pipes to another house with access to water.

Constraints:

    ...