Guest User

Untitled

a guest
Oct 18th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.58 KB | None | 0 0
  1. import math
  2. import heapq as hq
  3.  
  4. def prim(G):
  5. n=len(G)
  6. dist=[math.inf]*n
  7. path=[-1]*n
  8. visited=[False]*n
  9. q=[]
  10. dist[0]=0
  11. hq.heappush(q,(0,0))
  12. while len(q)>0:
  13. _, u= hq.heappop(q)
  14. if not visited[u]:
  15. for v,w in G[u]:
  16. if not visited[v] and w < dist[v]:
  17. dist[v]=w
  18. path[v]=u
  19. hq.heappush(q,(w,v))
  20.  
  21. return path, dist
  22.  
  23. G=[[(1,2),(2,3),(4,6)], #arco de 0 a 1 que pesa 2... de 0 a 2
  24. [(0,2),(4,2),(5,3)],
  25. [(0,3),(4,1),(3,5)],
  26. [(2,5),(4,5),(5,6)],
  27. [(0,6),(1,2),(2,1),(3,5),(5,4)],
  28. [(1,3),(3,6),(4,4)]]
  29.  
  30. print(prim(G))
Add Comment
Please, Sign In to add comment