【发布时间】: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