Optimize Water Distribution

Hard · Advanced Graphs · Union Find · Graph · Heap (Priority Queue) · Minimum Spanning Tree

Problem

A village has n houses numbered 1 to n. Every house needs water, which it can get in one of two ways:

Return the minimum total cost to supply water to every house.

Examples

Input: n = 3, wells = [2,5,4], pipes = [[1,2,1],[2,3,3]]
Output: 6

Build a well at house 1 (2) and lay both pipes (1 + 3), for 6.

Input: n = 2, wells = [1,1], pipes = [[1,2,5]]
Output: 2

Two wells cost 2, cheaper than any pipe.

Input: n = 2, wells = [4,9], pipes = [[1,2,7],[1,2,2]]
Output: 6

A well at house 1 plus the cheaper of the two parallel pipes costs 6.

Constraints

Approaches

Follow-up

The virtual source is the whole trick: it turns a choice between two kinds of cost into a single spanning tree. The use cases add houses that already have water (free edges from the source) and give every pair of houses a price, where Prim's O(n^2) beats sorting all the pairs.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…