簡體   English   中英

這個 dijkstra 算法的時間復雜度?

[英]Time Complexity of this dijkstra algorithm?

看到優先隊列可以變得和 |E| 一樣大,這個 Dijkstra 代碼的時間復雜度是多少? (節點可能會多次添加到優先級隊列中)我想推斷 while 循環內的時間復雜度。

def shortestReach(n, edges, start,target):

    adjList = collections.defaultdict(list)

    for parent, child, cost in edges:
        parent -= 1
        child -= 1
        adjList[parent].append((child, cost))
        adjList[child].append((parent, cost))

    priorityQueue = queue.PriorityQueue()
    priorityQueue.put((0, start))
    visited = set()
    while priorityQueue.qsize() > 0:
        costPar, parent = priorityQueue.get()

        if parent == target:
            return costPar

        if parent in visited:
            continue

        for adj in adjList[parent]:
            child, cost = adj
            if child not in visited:
                priorityQueue.put((cost + costPar, child))

        visited.add(parent)

我的想法:由於priorityQueue 可以變得和|E| 一樣大,那么下面這行最多可以發生|E| 次但從隊列中取出的節點不會被處理,因為我們有一個訪問集檢查。 所以它是 |E|log|E|

costPar, parent = priorityQueue.get()

下面的 for 循環最多可以在 |E| 處運行次,因為每個節點僅因訪問集而被處理一次,因此推理是它最多可以占用 |E|log|E| 最多次數

for adj in adjList[parent]:
            child, cost = adj
            if child not in visited:
                priorityQueue.put((cost + costPar, child))

總時間復雜度為 2*|E|log|E| -> O(|E|log|E|)?

內循環至多為每個頂點執行一次。 它的總迭代次數是每個頂點的度數之和,等於邊數的兩倍。 結果最多執行2*E次。

priorityQueue.put((cost + costPar, child))在堆中插入一個節點,這是一個O(log(size_of_heap))操作。 注意size_of_heap<=E

結合以上,我們得到O(|E| * log |E|)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM