首页 > 其他分享 >LeetCode 1168. Optimize Water Distribution in a Village

LeetCode 1168. Optimize Water Distribution in a Village

时间:2024-06-03 13:11:11浏览次数:26  
标签:parent int house pipes 1168 wells Water cost Optimize

原题链接在这里:https://leetcode.com/problems/optimize-water-distribution-in-a-village/description/

题目:

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, and there could be multiple valid connections between the same two houses with different costs.

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],[1,2,2]]
Output: 2
Explanation: We can supply water with cost two using one of the three options:
Option 1:
  - Build a well inside house 1 with cost 1.
  - Build a well inside house 2 with cost 1.
The total cost will be 2.
Option 2:
  - Build a well inside house 1 with cost 1.
  - Connect house 2 with house 1 with cost 1.
The total cost will be 2.
Option 3:
  - Build a well inside house 2 with cost 1.
  - Connect house 1 with house 2 with cost 1.
The total cost will be 2.
Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose the cheapest option. 

Constraints:

  • 2 <= n <= 104
  • wells.length == n
  • 0 <= wells[i] <= 105
  • 1 <= pipes.length <= 104
  • pipes[j].length == 3
  • 1 <= house1j, house2j <= n
  • 0 <= costj <= 105
  • house1j != house2j

题解:

Let us assume there is no wells. Transform all the wells cost to the edges.
There is a hidden house, house 0. All the wells cost are the edges cost from house 0.

Then along with piples cost, we can sort all the edges cost.

Then we want to connect the components. For a new edge, if two nodes are not connected, use this edge cost to connect since it is the cheapest.

Time Complexity: O(mlogm). m = piples.length + n.

Space: O(m).

AC Java:

 1 class Solution {
 2     int[] parent;
 3     public int minCostToSupplyWater(int n, int[] wells, int[][] pipes) {
 4         parent = new int[n + 1];
 5         List<int[]> edges = new ArrayList<>();
 6         for(int i = 0; i < n; i++){
 7             parent[i + 1] = i + 1;
 8             edges.add(new int[]{0, i + 1, wells[i]});
 9         }
10         
11         for(int[] pipe : pipes){
12             edges.add(pipe);
13         }
14         
15         Collections.sort(edges, (a, b) -> Integer.compare(a[2], b[2]));
16         
17         int res = 0;
18         for(int [] e : edges){
19             int x = root(e[0]);
20             int y = root(e[1]);
21             if(x != y){
22                 res += e[2];
23                 parent[x] = y;
24             }
25         }
26         
27         return res;
28     }
29     
30     private int root(int i){
31         if(i != parent[i]){
32             parent[i] = root(parent[i]);
33         }
34         
35         return parent[i];
36     }
37 }

 

标签:parent,int,house,pipes,1168,wells,Water,cost,Optimize
From: https://www.cnblogs.com/Dylan-Java-NYC/p/18228627

相关文章

  • 力扣1168水资源优化
    题目这个题目首先有节点,有双向边,而且要求最少总成本,那么我们最先想到的应该是最小生成树。算法逻辑 在最小生成树中有一个prim算法,个人觉得是和dijkstra非常相似甚至一模一样的,基于贪心思想的一种算法。prim的算法过程:首先找到一个一定存在的节点,然后从这个结点开始......
  • 高精度+高精度(信息学奥赛1168)
    #include<iostream>#include<cmath>#include<vector>usingnamespacestd;intmain(){stringa,b;cin>>a>>b;boola1=true,b1=true;for(inti=0;i<max(a.size(),b.size());i++){if(i<a.size()......
  • scipy_optimize_curve_fit 拟合多维曲面问题_scipy leastsq 拟合曲面
    CSDN搬家失败,手动导出markdown后再导入博客园在做模板匹配算法过程中,想要通过拟合高斯曲面的方式实现亚像素精度。初始代码如下#创建一个函数模型用来生成数据deffunc1(x,a,b,c,d):r=a*np.exp(-((x[0]-b)**2+(x[1]-d)**2)/(2*c**2))......
  • SciTech-BigDataAIML-Tensorflow-模型的训练与评估: tf.keras.losses + tf.keras.optim
    模型的训练:tf.keras.losses和tf.keras.optimizer定义一些模型超参数:num_epochs=5batch_size=50learning_rate=0.001实例化模型和数据读取类,并实例化一个tf.keras.optimizer的优化器(这里使用常用的Adam优化器):model=MLP()data_loader=MNISTLoader()optimiz......
  • SciTech-BigDataAIML-Tensorflow-Optimizer:优化器
    https://keras.io/api/optimizers/OptimizersAvailableoptimizers:SGDRMSpropAdamAdamWAdadeltaAdagradAdamaxAdafactorNadamFtrlLionLossScaleOptimizerUsagewithcompile()&fit()Anoptimizerisoneofthetwoargumentsrequiredforcompilin......
  • Oracle-HWM(High Water Mark) 高水位解读
    转自:https://cloud.tencent.com/developer/article/1861861Oracle的逻辑存储管理ORACLE在逻辑存储上分4个粒度,由大到小为:表空间,段,区和块.块Block块:是粒度最小的存储单位,现在标准的块大小是8K,ORACLE每一次I/O操作也是按块来操作的,也就是说当ORACLE从数据文件读数......
  • SciTech-BigDataAIML-TensorFlow-Model的编译:设置(LossFunction+Optimizer+Metrics)与
    机器学习|model.compile()用法model.compile()的作用:为经过设计的Model(神经网络模型)设置好:loss损失函数、optimizer优化器、metrics准确性评价函数。并且进行编译;Optimizers优化器:Optimizer的主要功能是作用在GD(梯度下降)的过程,使得Gradient(梯度)更快(快速......
  • text_blind_watermark%3A 给文本加隐水印
    项目简介文本隐水印,用来把一段信息嵌入到一段明文中,使信息隐密不可见,并且旁人无法察觉到嵌入后明文的变化。经测试,在这些场景下信息隐藏比较完美MacBook版本的Chrome浏览器,包括知乎网页版、微博网页版等。微信、钉钉。Mac/Iphone版均可苹果备忘录用Chrome打开github......
  • text_blind_watermark%3A 给文本加隐水印
    项目简介文本隐水印,用来把一段信息嵌入到一段明文中,使信息隐密不可见,并且旁人无法察觉到嵌入后明文的变化。经测试,在这些场景下信息隐藏比较完美MacBook版本的Chrome浏览器,包括知乎网页版、微博网页版等。微信、钉钉。Mac/Iphone版均可苹果备忘录用Chrome打开github......
  • C. Mixing Water
    https://codeforces.com/contest/1359/problem/C题意:给h和c两个数,并且操作顺序必须是hchchchch...对这些操作求和后除以操作次数得到均值,要求这个均值尽可能的接近t。问在最接近t的情况下,最少需要进行多少次操作。思路:如果(h+c)/2>=t,那么则只需两次操作最优。如果h==t,......