15_chiton.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env python3
  2. import sys
  3. from heapq import heappop, heappush
  4. def parse(content):
  5. w = content.find('\n') + 1
  6. return list(map(int, content.replace('\n', '0') + w * '0')), w
  7. def shortest_path(risk, w, source, destination):
  8. dist = [1 << 31] * len(risk)
  9. visited = [False] * len(risk)
  10. visited[source] = True
  11. prev = {}
  12. work = [(0, source)]
  13. while work:
  14. udist, u = heappop(work)
  15. if u == destination:
  16. total = 0
  17. while u != source:
  18. total += risk[u]
  19. u = prev[u]
  20. return total
  21. for nb in (u - w, u - 1, u + 1, u + w):
  22. if risk[nb] and not visited[nb]:
  23. visited[nb] = True
  24. alt = udist + risk[nb]
  25. if alt < dist[nb]:
  26. dist[nb] = alt
  27. prev[nb] = u
  28. heappush(work, (alt, nb))
  29. def traverse(risk, w):
  30. return shortest_path(risk, w, 0, len(risk) - w - 2)
  31. def repeat(risk, w, times):
  32. new = []
  33. for y in range(times):
  34. for i in range(0, len(risk) - w, w):
  35. for x in range(times):
  36. new.extend((r + x + y - 1) % 9 + 1 for r in risk[i:i + w - 1])
  37. new.append(0)
  38. wnew = (w - 1) * times + 1
  39. new.extend([0] * wnew)
  40. return new, wnew
  41. risk, w = parse(sys.stdin.read())
  42. print(traverse(risk, w))
  43. print(traverse(*repeat(risk, w, 5)))