村庄内有n户人家,我们可以通过挖井或者建造水管向每家供水。
对于每户人家i,我们可以通过花费 wells[i] 直接在其房内挖水井,或者通过水管连接到其他的水井。每两户住户间铺设水管的费用通过 pipes 数组表示。 pipes[i] = [house1, house2, cost] 表示住户1到住户2间铺设水管的费用为cost。
请求出所有住户都能通水的最小花费。
示例1:
输入: n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]]
输出: 3
解释:
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.
提示:
1 <= n <= 10000
wells.length == n
0 <= wells[i] <= 10^5
1 <= pipes.length <= 10000
1 <= pipes[i][0], pipes[i][1] <= n
0 <= pipes[i][2] <= 10^5
pipes[i][0] != pipes[i][1]
classSolution:defminCostToSupplyWater(self,n:int,wells: List[int],pipes: List[List[int]]) ->int: union_find ={i: i for i inrange(n +1)}deffind(x):return x if x == union_find[x]elsefind(union_find[x])defunion(x,y): px =find(x) py =find(y) union_find[px]= py graph_wells = [[cost,0, i] for i, cost inenumerate(wells, 1)] graph_pipes = [[cost, i, j] for i, j, cost in pipes] min_costs =0for cost, x, y insorted(graph_wells + graph_pipes):iffind(x)==find(y):continueunion(x, y) min_costs += cost n -=1if n ==0:return min_costs