Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. import math
  2.  
  3. graph = {}
  4. coords = {}
  5. n = int(input())
  6. ancestors = {}
  7. MAXI = float(10 ** 9)
  8. dist = {}
  9. used = {}
  10. def restore_path(v, to, ancestors):
  11.     start = to
  12.     path = []
  13.     while start != -1:
  14.         path.append(start)
  15.         start = ancestors[start]
  16.     path = path[::-1]
  17.     return path[:]
  18. def get_len(first, second, coords):
  19.     return math.sqrt((coords[first][0] - coords[second][0]) ** 2 + (coords[first][1] - coords[second][1]) ** 2)
  20. def dijkstra(v, to, graph, dist, used, ancestors):
  21.     dist[v] = 0
  22.     for i in range(n):
  23.         mini, ind = MAXI, None
  24.         for j in dist:
  25.             if mini > dist[j] and (not used[j]):
  26.                 mini = dist[j]
  27.                 ind = j
  28.         if ind is None or mini == MAXI:
  29.             break
  30.         used[ind] = True
  31.         for city in graph[ind]:
  32.             len_ = get_len(city, ind, coords)
  33.             if dist[city] > dist[ind] + len_:
  34.                 dist[city] = dist[ind] + len_
  35.                 ancestors[city] = ind
  36. for i in range(n):
  37.     input_parts = input().split(' ')
  38.     city = input_parts[0]
  39.     coord_x = int(input_parts[1])
  40.     coord_y = int(input_parts[2])
  41.     graph[city] = []
  42.     dist[city] = MAXI
  43.     used[city] = False
  44.     ancestors[city] = -1
  45.     coords[city] = [coord_x, coord_y]
  46.     for j in range(3, len(input_parts)):
  47.         if len(input_parts[j]) > 0:
  48.             graph[city].append(input_parts[j])
  49. v, to = input().split()
  50. dijkstra(v, to, graph, dist, used, ancestors)
  51. if dist[to] == MAXI:
  52.     print("Path:\nNo way")
  53. else:
  54.     print("Path is not greater than", int(dist[to] + 1))
  55.     print("Path:")
  56.     path = restore_path(v, to, ancestors)
  57.     for x in path:
  58.         print(x, end = ' ')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement