想用python實現一下單源最短路的Dijkstra算法,卻發現不會使用python的優先隊列,於是學習了一下。
學習的博客:https://www.yangyanxing.com/article/priorityqueue_in_python.html
https://blog.csdn.net/liu2012huan/article/details/53264162
博主想簡要小結一下,先說明,博主並沒有深刻了解python堆/隊列的實現,沒有認真讀過官方文檔,沒看過源碼什么的。只是博主照着上面兩篇博文照葫蘆畫瓢,給一個最簡單的使用方式而已。
1 from queue import Queue,PriorityQueue 2 3 # 使用heapq實現優先隊列 4 #定義一個可比較對象 5 class pqueue: 6 def __init__(self,x,y): 7 self.x = x 8 self.y = y 9 10 def __lt__(self, other): #定義了<,像C++的重載<運算符 11 return self.x<other.x 12 13 14 def main(): 15 pq = PriorityQueue() 16 while 1: 17 opt=int(input()) 18 if opt==0: #輸入0,結束測試 19 break 20 if opt==1: #輸入1,輸入數字對 21 x,y=map(int,input().split()) 22 pq.put(pqueue(x,y)) #插入數據 23 if opt==2: #輸入2,輸出優先隊列隊頭 24 tmp=pq.get() 25 print(tmp.x,tmp.y) #提取隊頭 26 27 28 if __name__=="__main__": 29 main()
然后是用法示例,用python實現Dijkstra算法:
1 from queue import Queue,PriorityQueue 2 3 class pair: 4 def __init__(self,x,y): 5 self.x = x 6 self.y = y 7 8 def __lt__(self, other): 9 return self.y<other.y 10 11 class edge: 12 def __init__(self,x,y,z): 13 self.x = x 14 self.y = y 15 self.z = z 16 17 18 def Dijkstra(n,s,edges): 19 pq = PriorityQueue() 20 vis=[0]*(n+1) 21 dis=[0x3f3f3f3f]*(n+1) 22 dis[s]=0 23 pq.put(pair(s,0)) 24 while not pq.empty(): 25 now=pq.get() 26 if vis[now.x]==1: 27 continue 28 vis[now.x]=1 29 for e in edges[now.x]: 30 if dis[now.x]+e.z<dis[e.y]: 31 dis[e.y]=dis[now.x]+e.z 32 pq.put(pair(e.y,dis[e.y])) 33 INF=(1<<31)-1 34 for i in range(1,n+1): 35 print(dis[i] if dis[i]!=0x3f3f3f3f else INF,end=' ') 36 37 def main(): 38 n,m,s=map(int,input().split()) 39 edges=[] 40 for _ in range(n+1): 41 edges.append([]) 42 for _ in range(m): 43 x,y,z=map(int,input().split()) 44 edges[x].append(edge(x,y,z)) 45 Dijkstra(n,s,edges) 46 47 48 if __name__=="__main__": 49 main()