在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ There are For each house Find 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. Constraints:
村里面一共有 对于每个房子
请你帮忙计算为所有房子都供水的最低总成本。
示例: 输入:n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]] 输出:3 解释: 上图展示了铺设管道连接房屋的成本。 最好的策略是在第一个房子里建造水井(成本为 1),然后将其他房子铺设管道连起来(成本为 2),所以总成本为 3。
提示:
1260 ms 1 class Solution { 2 func minCostToSupplyWater(_ n: Int, _ wells: [Int], _ pipes: [[Int]]) -> Int { 3 var pipes = pipes 4 var ds:DJSet = DJSet(n + 2) 5 var m:Int = pipes.count 6 pipes += [[Int]](repeating:[Int](),count:n) 7 for i in 0..<n 8 { 9 pipes[m+i] = [n+1, i+1, wells[i]] 10 } 11 pipes.sort(by:{ 12 $0[2] < $1[2] 13 }) 14 var ans:Int = 0 15 for e in pipes 16 { 17 if !ds.union(e[0], e[1]) 18 { 19 ans += e[2] 20 } 21 } 22 return ans 23 } 24 } 25 26 public class DJSet 27 { 28 var upper:[Int] 29 30 init(_ n:Int) 31 { 32 upper = [Int](repeating:-1,count:n) 33 } 34 35 func root(_ x:Int) -> Int 36 { 37 if(upper[x] < 0) 38 { 39 return x 40 } 41 else 42 { 43 upper[x] = root(upper[x]) 44 return upper[x] 45 } 46 } 47 48 func equiv(_ x:Int,_ y:Int) -> Bool 49 { 50 return root(x) == root(y) 51 } 52 53 func union(_ x:Int,_ y:Int) -> Bool 54 { 55 var x:Int = root(x) 56 var y:Int = root(y) 57 if x != y 58 { 59 if upper[y] < upper[x] 60 { 61 var d:Int = x 62 x = y 63 y = d 64 } 65 upper[x] += upper[y] 66 upper[y] = x 67 } 68 return x == y 69 } 70 71 func count() -> Int 72 { 73 var ct:Int = 0 74 for u in upper 75 { 76 if u < 0 77 { 78 ct += 1 79 } 80 } 81 return ct 82 } 83 }
|
请发表评论