LC: 1168. Optimize Water Distribution in a Village
1168. Optimize Water Distribution in a Village
There are n houses in a village. We want to supply water for all the houses by building wells and laying pipes.
For each house i, we can either build a well inside it directly with cost wells[i - 1] (note the -1 due to 0-indexing), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array pipes, where each pipes[j] = [house1j, house2j, costj] represents the cost to connect house1j and house2j together using a pipe. Connections are bidirectional.
Return the minimum total cost to supply water to all houses.
Example 1:
Input: n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]]
Output: 3
Explanation:
The image shows the costs of connecting houses using pipes.
The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3.Example 2:
Input: n = 2, wells = [1,1], pipes = [[1,2,1]]
Output: 2Constraints:
2 <= n <= 104wells.length == n0 <= wells[i] <= 1051 <= pipes.length <= 104pipes[j].length == 31 <= house1j, house2j <= n0 <= costj <= 105house1j != house2j
The Essence: Man kann dieses Problem durch Graphentheorie interpretieren. “Ein Spannbaum [...] ist in der Graphentheorie ein Teilgraph eines ungerichteten Graphen, der ein Baum ist und alle Knoten dieses Graphen enthält.”
Hier haben auch die Knoten Gewichte, die Kosten für Wellen. Um diese Tatsache in einem Graph mit gewichteten Kanten zu repräsentieren, kann man einen virtuellen Knoten verwenden und der Abstand von diesem Knoten als das Gewicht des Knotens bezeichnen. Jetzt soll man den minimalen Spannbaum einschließlich dieses virtuelles Knotens finden.
1168. Optimize Water Distribution in a Village:
Details:
Die zwei einfachsten Methode für die Bestimmung des minimalen Spannbaums ist der Algorithmus von Prim und der Algorithmus von Kruskal. Es ist hilfreich für den Problemlöser, diese Algorithmen zu lernen.
Default Code:
Last updated
