【问题标题】:Time complexity of the following Prim's algorithm implementation以下 Prim 算法实现的时间复杂度
【发布时间】:2017-07-12 16:22:03
【问题描述】:

以下代码的时间复杂度是多少?我正在使用图形和优先级队列的邻接矩阵表示来实现 prim 算法。在我看来,时间复杂度是:堆最多可以增长到(n-1)的大小,当源连接到其他每个节点,并且在内部循环中,邻接矩阵的成本是 O(n),所以总共是:它的 O((n-1) * n) -> O(n^2),其中 n 是节点数。这个计算正确吗?因此,由于邻接矩阵,堆并没有改善我最坏情况的运行时间?

from graph import adj_mtx, AP
import heapq as hq

lv, visited, h = float('inf'), {}, []  # lv stands for 'large_value', h is the heap


def prims_mst(adj_matrix, src):
    hq.heappush(h, (0, (src, None)))  # O(logn)
    curr_dist = {item.value: lv if item.value != src else 0 for item in AP}  # AP is the enumeration of nodes

    while len(h) != 0:
        curr_nd = hq.heappop(h)[1][0]  # first element of the tuple is the value, second is the node  # O(1)
        visited[curr_nd] = True  # O(1)
        for nd, dst in enumerate(adj_matrix[src]):  # O(n) -> n is the number of nodes
            if nd not in visited and curr_dist[nd] > curr_dist[curr_nd] + adj_matrix[curr_nd][nd]:
                curr_dist[nd] = curr_dist[curr_nd] + adj_matrix[curr_nd][nd]
                hq.heappush(h, (curr_dist[nd], (nd, curr_nd)))  # O(logn)
        print h

【问题讨论】:

  • 您认为时间复杂度是多少,为什么?我们不是来为您工作的。
  • 我已更新问题以包含我的计算
  • 你遗漏了“为什么”部分。
  • 更新了我的问题

标签: python time-complexity priority-queue adjacency-matrix prims-algorithm


【解决方案1】:

这取决于 len(h) 的作用、它返回的值以及 while 的行为方式。当你发现这一点时,你将它与来自 for 的 o(n) 和来自 hq.headpush 的 o(log n) 相乘,你就会得到你的复杂性 它类似于 O(x*nlog n),其中 X 是一段时间内完成所需要的步骤。

【讨论】:

  • len(h) 应该是 O(1) 操作。它只是返回堆的长度。
  • while 的目的是什么?只要你有一个堆就运行?
  • 是的。只要堆中还有元素。
  • 似乎是 O(n^2log n)。
猜你喜欢
  • 2010-10-17
  • 2012-10-19
  • 1970-01-01
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多