Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from heapq import *
- from collections import defaultdict
- from sys import stdin
- def readNums():
- return [int(x) for x in stdin.readline().split()]
- planets, no_roads = readNums()
- # if we do roads[key].append(value) and key wasn't set before, we get roads[key] == [value]
- # avoids doing
- # if key in roads: roads[key].append(value)
- # else: roads[key] = [value]
- roads = defaultdict(list)
- for _ in range(no_roads):
- a, b, cost = readNums()
- roads[a-1].append((b-1, cost))
- roads[b-1].append((a-1, cost))
- waittimes = []
- for _ in range(planets):
- times = readNums()
- waittimes.append(set(times[1:]))
- def dijkstra(planets, roads, waittimes):
- " Returns an list containing the distances of cities from source "
- # assume cities are numbered [0..cities-1]
- times = [10**10] * planets # at the beginning, mark distances as infinity
- times[0] = 0
- heap = [(0, 0)] # time as first element, planet as second
- while len(heap) > 0:
- time, planet = heappop(heap) # remove the element with smallest time
- #print time, planet
- if time > times[planet]: continue # skip, we were here faster before
- while time in waittimes[planet]: # travellers arriving
- time += 1
- for nextPlanet, cost in roads[planet]:
- if times[nextPlanet] > time + cost: # if we get there faster this way
- times[nextPlanet] = time + cost
- heappush(heap, (time + cost, nextPlanet)) # next place to the heap
- return times
- times = dijkstra(planets, roads, waittimes)
- if times[planets-1] < 10**10:
- print times[planets-1]
- else:
- print -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement