📣 独立日限时特惠: VIP通行证立减$68
查看: 968| 回复: 3
跳转到指定楼层
上一主题 下一主题
收起左侧

[树/链表/图] leetcode 743求解

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
leetcode: 743        Network Delay Time
我写了两个版本,这个是错的:
  1. class Solution:
  2.     def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
  3.         graph = collections.defaultdict(list)
  4.         for source, target, time in times:
  5.             graph[source].append((time, target))

  6.         q = []
  7.         heapq.heappush(q, (0, K))
  8.         arrival = {}
  9.         arrival[K] = 0
  10.         while q:
  11.             time, node = heapq.heappop(q)
  12.             for t, n in graph[node]:
  13.                 if n not in arrival:
  14.                     arrival[n] = time + t
  15.                     heapq.heappush(q, (time + t, n))
  16.         res = 0
  17.         if len(arrival) < N:
  18.             return -1
  19.         for i, v in arrival.items():
  20.             res = max(res, v)
  21.         return res
复制代码


这个是对的:
  1. class Solution:
  2.     def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
  3.         graph = collections.defaultdict(list)
  4.         for source, target, time in times:
  5.             graph[source].append((time, target))

  6.         q = []
  7.         heapq.heappush(q, (0, K))
  8.         arrival = {}
  9.         while q:
  10.             time, node = heapq.heappop(q)
  11.             if node not in arrival:
  12.                 arrival[node] = time
  13.                 for t, n in graph[node]:
  14.                     heapq.heappush(q, (t+ time, n))
  15.         res = 0
  16.         if len(arrival) < N:
  17.             return -1
  18.         for i, v in arrival.items():
  19.             res = max(res, v)
  20.         return res
复制代码


请各位帮忙指出为哈第一个错了?谢谢!

补充内容 (2019-5-14 14:04):

想明白了,第一个更新节点到达的时间太快了,应该交给priority queue延迟更新才能得到最短路径

上一篇:请教一道SQL题,OA遇到了,做不起然后挂了
下一篇:有刷题Tutorial的推荐嘛?
🔗
 楼主| luciferth000 2019-5-14 14:04:37 | 只看该作者
全局:
想明白了,第一个更新节点到达的时间太快了,应该交给priority queue延迟更新才能得到最短路径。
回复

使用道具 举报

🔗
337845818 2019-5-14 21:51:03 | 只看该作者
全局:
MST
https://en.wikipedia.org/wiki/Minimum_spanning_tree

其实用不用pq都没关系..
回复

使用道具 举报

🔗
孙行者 2019-5-15 13:07:31 | 只看该作者
全局:
这题用bellman-ford解就行了,就是求到达所有节点的最小可能的值。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表