05_food.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python3
  2. import sys
  3. from itertools import chain
  4. def parse(inp):
  5. yield list(map(int, next(inp).split()[1:]))
  6. yield [[list(map(int, line.split())) for line in par.split('\n')[1:]]
  7. for par in inp.read().strip().split('\n\n')]
  8. def apply(maps, start, end):
  9. for dst, src, mapsize in maps:
  10. delta = dst - src
  11. mapend = src + mapsize
  12. r = start, end
  13. if src <= start < mapend:
  14. if end <= mapend:
  15. yield start + delta, end + delta
  16. return
  17. else:
  18. yield start + delta, dst + mapsize
  19. start = mapend
  20. elif src < end <= mapend:
  21. yield dst, end + delta
  22. end = src
  23. elif start < src and end > mapend:
  24. yield from apply(maps, start, src)
  25. yield dst, dst + mapsize
  26. start = mapend
  27. yield start, end
  28. def min_location(seeds, steps):
  29. ranges = seeds
  30. for maps in steps:
  31. ranges = list(chain.from_iterable(apply(maps, *r) for r in ranges))
  32. return min(start for start, end in ranges)
  33. seeds, steps = parse(sys.stdin)
  34. print(min_location([(s, s + 1) for s in seeds], steps))
  35. ranges = [(s, s + size) for s, size in zip(seeds[::2], seeds[1::2])]
  36. print(min_location(ranges, steps))