Whyt是Dijkstra与堆O(v)而不是(v+ e)的空间复杂性吗?

发布于 2025-02-03 12:28:37 字数 838 浏览 3 评论 0原文

关于dijkstra,带有最小堆(优先队列),

import heapq

graph = [
  [(1, 5), (2, 3)],
  [(3, 3), (2, 2)],
  [(4, 4), (5, 2), (3, 7)],
  [(4, 1)],
  [],
  [(4, 5)]
]
v = len(graph)
dist = [math.inf] * v

def dijkstra(start):
  # Init dist / heap / heap with start
  dist[start] = 0
  hq = [(0, start)]

  while hq:
    # pop current shortest distance node
    d, cur = heapq.heappop(hq) 
    if d > dist[cur]: continue # pass decided node
      
    for next, weight in graph[cur]:
      new_dist = dist[cur] + weight
      if new_dist < dist[next]:
        dist[next] = new_dist
        heapq.heappush(hq, (new_dist, next))

  for i in range(v): print(dist[i], end=" ") # print distance
      

我知道存储距离需要O(v)。 但是堆不需要o(e),因为它包含总共E?

因此,我认为空间复杂性是O(V+E)。 有什么问题吗?

谢谢

About Dijkstra with min heap(priority queue),,,

import heapq

graph = [
  [(1, 5), (2, 3)],
  [(3, 3), (2, 2)],
  [(4, 4), (5, 2), (3, 7)],
  [(4, 1)],
  [],
  [(4, 5)]
]
v = len(graph)
dist = [math.inf] * v

def dijkstra(start):
  # Init dist / heap / heap with start
  dist[start] = 0
  hq = [(0, start)]

  while hq:
    # pop current shortest distance node
    d, cur = heapq.heappop(hq) 
    if d > dist[cur]: continue # pass decided node
      
    for next, weight in graph[cur]:
      new_dist = dist[cur] + weight
      if new_dist < dist[next]:
        dist[next] = new_dist
        heapq.heappush(hq, (new_dist, next))

  for i in range(v): print(dist[i], end=" ") # print distance
      

I understand O(V) is needed for storing distance.
But doesn't heap need O(E) because it contains a total of E?

So I think space complexity is O(V+E).
Is there anything wrong?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

是伱的 2025-02-10 12:28:37

O(v)是Dijkstra实现的空间复杂性,该实现使用了带有减少键操作的堆,并使用降低 - 键来更新现有的堆条目,而不是为同一节点添加多个条目。通过这样的实现,堆每个顶点最多将有一个条目,而不是每个边缘的一个条目。

O(V) is the space complexity for a Dijkstra implementation that uses a heap with a decrease-key operation, and uses decrease-key to update existing heap entries instead of adding multiple entries for the same node. With such an implementation, the heap will have at most one entry per vertex, not one entry per edge.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文