Skip to content
BytePatterns

Water Every House

HardGraphs#prim#virtual-node~40m

Problem

A village has n houses numbered 1 to n. House i can get water from a well of its own at cost wells[i - 1], or through pipes: a pipe [a, b, c] joins houses a and b in both directions at cost c. Return the smallest total cost that gives every house water, either from its own well or through a chain of pipes leading to a house that has a well.

Examples

Input:  wells = [3, 4, 2], pipes = [[1, 2, 1], [2, 3, 5]]
Output: 6
Why:    wells at houses 1 and 3, plus the pipe from 1 to 2
Input:  wells = [1, 1], pipes = [[1, 2, 10]]
Output: 2
Why:    two cheap wells beat the expensive pipe
Input:  wells = [5], pipes = []
Output: 5
Why:    edge case, one house and no pipes

Hints

0 / 3

Stuck on the idea rather than the code? Prim's Spanning Tree covers it.