博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode题解(1168):水资源分配优化(Python)
阅读量:1901 次
发布时间:2019-04-26

本文共 1081 字,大约阅读时间需要 3 分钟。

题目:(困难)

标签:图、Prim算法、Kruskal算法

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( N l o g N ) O(NlogN) O(NlogN) O ( N ) O(N) O(N) 184ms (86.67%)
Ans 2 (Python)
Ans 3 (Python)

解法一:

import collectionsimport heapqfrom typing import Listclass Solution:    def minCostToSupplyWater(self, n: int, wells: List[int], pipes: List[List[int]]) -> int:        graph = collections.defaultdict(dict)        for edge in pipes:            if edge[1] not in graph[edge[0]] or edge[2] < graph[edge[0]][edge[1]]:                graph[edge[0]][edge[1]] = edge[2]                graph[edge[1]][edge[0]] = edge[2]        # 添加所有房屋到地下水结点的距离        for i, well in enumerate(wells):            graph[0][i + 1] = well        ans = 0        waiting = {
i for i in range(0, n + 1)} heap = [(0, 0)] while heap and waiting: v1, n1 = heapq.heappop(heap) if n1 in waiting: ans += v1 waiting.remove(n1) for n2, v2 in graph[n1].items(): if n2 in waiting: heapq.heappush(heap, (v2, n2)) return ans

转载地址:http://nxkcf.baihongyu.com/

你可能感兴趣的文章
facebook市场营销SDK之个人理解 Star.hou原创
查看>>
Redis AOF之重写 Star.hou原创
查看>>
Redis之主从配置的心跳 Star.hou原创
查看>>
vim or sed字符串批量替换
查看>>
redis之队列处理回滚记录 star.Hou
查看>>
Laravel repository数据仓库使用 Star.hou红楼一梦
查看>>
Google Analytics Reporting API V4 开发之笔记 star.Hou
查看>>
Laravel之文件上传
查看>>
Redis 3.2.3 源码安装(centos6.8)
查看>>
全站翻译分享---Localize平台的使用方式整理--Star.hou
查看>>
根据浏览器语言自动切换多语言站点 Star.hou
查看>>
Mac 忘记root密码解决方法--Star.hou
查看>>
elasticSearch 批量添加索引的数量 Star.hou
查看>>
阿里云存储OSS对接PHP之Star.hou
查看>>
PHP Imap模块删除函数 --Star.hou
查看>>
快速搭建Dev / Test / Porduct 环境妙招--Star.hou
查看>>
RetinaNet:模型被巨量简单样本“绑架”了怎么办,在线等 Focal Loss 来帮忙
查看>>
SSD:虽然我适应多尺度,可是数据扩增对我可太重要了/(ㄒoㄒ)/~~
查看>>
详解 TensorFlow TFLite 移动端(安卓)部署物体检测 demo(1)——照本宣科
查看>>
详解 TensorFlow TFLite 移动端(安卓)部署物体检测 demo(2)——量化模型
查看>>