AlgoFrames

Supply water to every house

Standard · Write code · about 20 min

Houses are numbered 1 to n. Digging a well at house i costs wells[i - 1]. A pipe [a, b, w] joins houses a and b for cost w. Every house needs water from its own well or through pipes from a house that has it. Return the minimum total cost.

Example 1

Input:

[3,[1,2,2],[[1,2,1],[2,3,1]]]

Output:

3

Well at house 1 (1), pipes 1-2 (1) and 2-3 (1).

Example 2

Input:

[2,[1,1],[[1,2,1],[1,2,2]]]

Output:

2

One well and the cheaper pipe, or two wells: both cost 2.

Constraints

  • 1 ≤ n ≤ 1000
  • wells.length = n
  • 0 ≤ pipes.length ≤ 2000
  • 1 ≤ costs ≤ 100,000
  • Two houses may be joined by more than one pipe.

Learn the idea first: Prim's algorithm, a visual lesson.

More Prim's algorithm problems