Advertisement
Guest User

Untitled

a guest
Feb 1st, 2015
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. from heapq import *
  2. from collections import defaultdict
  3. from sys import stdin
  4.  
  5. def readNums():
  6. return [int(x) for x in stdin.readline().split()]
  7.  
  8. planets, no_roads = readNums()
  9. # if we do roads[key].append(value) and key wasn't set before, we get roads[key] == [value]
  10. # avoids doing
  11. # if key in roads: roads[key].append(value)
  12. # else: roads[key] = [value]
  13. roads = defaultdict(list)
  14. for _ in range(no_roads):
  15. a, b, cost = readNums()
  16. roads[a-1].append((b-1, cost))
  17. roads[b-1].append((a-1, cost))
  18. waittimes = []
  19. for _ in range(planets):
  20. times = readNums()
  21. waittimes.append(set(times[1:]))
  22.  
  23. def dijkstra(planets, roads, waittimes):
  24. " Returns an list containing the distances of cities from source "
  25. # assume cities are numbered [0..cities-1]
  26. times = [10**10] * planets # at the beginning, mark distances as infinity
  27. times[0] = 0
  28. heap = [(0, 0)] # time as first element, planet as second
  29. while len(heap) > 0:
  30. time, planet = heappop(heap) # remove the element with smallest time
  31. #print time, planet
  32. if time > times[planet]: continue # skip, we were here faster before
  33. while time in waittimes[planet]: # travellers arriving
  34. time += 1
  35. for nextPlanet, cost in roads[planet]:
  36. if times[nextPlanet] > time + cost: # if we get there faster this way
  37. times[nextPlanet] = time + cost
  38. heappush(heap, (time + cost, nextPlanet)) # next place to the heap
  39. return times
  40.  
  41. times = dijkstra(planets, roads, waittimes)
  42. if times[planets-1] < 10**10:
  43. print times[planets-1]
  44. else:
  45. print -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement