Advertisement
pankovamg

0-1 BFS

Nov 21st, 2021
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. '''
  2. Дороги между разными хохяевами - по 1, иначе 0
  3. 10 11
  4. 1 1 1 1 2 1 1 2 2 1
  5. 1 2
  6. 2 8
  7. 8 10
  8. 10 6
  9. 6 9
  10. 5 9
  11. 4 5
  12. 4 9
  13. 3 4
  14. 3 7
  15. 7 1
  16. '''
  17. from collections import deque
  18. n, m = map(int, input().split())
  19. INF = 10**9
  20. dist = [INF] * (n+1)
  21. prev = [None] * (n+1)
  22. dist[1] = 0
  23. g = [[] for i in range(n+1)]
  24. a = [0] + list(map(int, input().split()))
  25. for i in range(m):
  26. x, y = map(int, input().split())
  27. w = 0
  28. if a[x] != a[y]:
  29. w = 1
  30. g[x].append((y, w))
  31. g[y].append((x, w))
  32.  
  33. q = deque()
  34. q.append(1)
  35. while q:
  36. v = q.popleft()
  37. for u, w in g[v]:
  38. if dist[v] + w < dist[u]:
  39. dist[u] = dist[v] + w
  40. prev[u] = v
  41. if w == 0:
  42. q.appendleft(u)
  43. else:
  44. q.append(u)
  45. if dist[n] != INF:
  46. path = []
  47. p = n
  48. while p != None:
  49. path.append(p)
  50. p = prev[p]
  51. print(dist[n], len(path))
  52. print(*path[::-1])
  53. else:
  54. print(-1)
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement