Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

41 linhas
1.0KB

  1. import random
  2. import heapq
  3. def solve(ns):
  4. heap = [(0, None, 0, d) for d in [1, 1j]]
  5. exhausted = set()
  6. while True:
  7. old_cost, _, old_pos, old_dir = heapq.heappop(heap)
  8. if old_pos == end:
  9. break
  10. key = old_pos, old_dir
  11. if key in exhausted:
  12. continue
  13. exhausted.add(key)
  14. for n in ns:
  15. new_pos = old_pos + old_dir * n
  16. if new_pos not in graph:
  17. break
  18. new_cost = old_cost + sum(graph[old_pos + i * old_dir] for i in range(1, n + 1))
  19. heapq.heappush(heap, (new_cost, random.random(), new_pos, old_dir * 1j))
  20. heapq.heappush(heap, (new_cost, random.random(), new_pos, old_dir / 1j))
  21. return old_cost
  22. text = open(0).read()
  23. graph = {
  24. complex(x, y): int(val)
  25. for y, row in enumerate(text.splitlines())
  26. for x, val in enumerate(row)
  27. }
  28. xmax = max(int(p.real) for p in graph)
  29. ymax = max(int(p.imag) for p in graph)
  30. end = complex(xmax, ymax)
  31. print(solve([1, 2, 3]))
  32. print(solve(list(range(4, 11))))