Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. def dist_min():
  2. """
  3. Gives the nearest node to the origin that is in the set
  4. """
  5. min = 10000000
  6. elem = -1
  7. for i in range(n):
  8. if i in set and distTo[i] <= min:
  9. min = distTo[i]
  10. elem = i
  11. return elem
  12.  
  13. def neighbors(node):
  14. """
  15. Return every neighbor of a node, with the weight of the edge that leads to it
  16. """
  17. ret = []
  18. for (f, t, edge) in paths:
  19. if f-1 == node:
  20. weight = edge + tasks[t-1]
  21. ret.append((t-1, weight))
  22. return ret
  23.  
  24. n = len(tasks)
  25. distTo = [10000000 for x in range(n)]
  26. distTo[0] = tasks[0] # distance to first task is its duration
  27. set = deque([0]) # set of nodes to explore. contains first task
  28.  
  29. while set: # while set is not empty
  30. min = dist_min() # take nearest node to explore
  31. set.remove(min) # it has been explored
  32. for neigh, weight in neighbors(min): # for all its neighbors
  33. if distTo[neigh] > distTo[min] + weight: # if a destination can be reached more quickly:
  34. distTo[neigh] = distTo[min] + weight # update that distance
  35. if not set.__contains__(neigh):
  36. set.append(neigh)
  37.  
  38. return distTo[n-1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement