10_bots.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python3
  2. import sys
  3. from collections import defaultdict, deque
  4. class Simulation:
  5. def __init__(self):
  6. self.bots = defaultdict(list)
  7. self.outputs = defaultdict(list)
  8. self.lows = {}
  9. self.highs = {}
  10. @classmethod
  11. def parse(cls, f):
  12. self = cls()
  13. dests = {'bot': self.bots, 'output': self.outputs}
  14. def set_dest(mapping, bot, ty, nr):
  15. dest = (self.bots if ty == 'bot' else self.outputs)
  16. mapping[bot] = (self.outputs, int(nr))
  17. for line in f:
  18. words = line.split()
  19. if words[0] == 'value':
  20. self.bots[int(words[-1])].append(int(words[1]))
  21. else:
  22. bot = int(words[1])
  23. self.lows[bot] = dests[words[5]], int(words[6])
  24. self.highs[bot] = dests[words[-2]], int(words[-1])
  25. return self
  26. def run(self):
  27. queue = deque(bot for bot, ch in self.bots.items() if len(ch) == 2)
  28. self.comparisons = {}
  29. def give(dest, nr, chip):
  30. dest[nr].append(chip)
  31. if dest == self.bots and len(dest[nr]) == 2:
  32. queue.append(nr)
  33. while queue:
  34. bot = queue.popleft()
  35. chips = self.bots[bot]
  36. if len(chips) == 2:
  37. chips.sort()
  38. self.comparisons[tuple(chips)] = bot
  39. give(*self.highs[bot], chips.pop())
  40. give(*self.lows[bot], chips.pop())
  41. sim = Simulation.parse(sys.stdin)
  42. sim.run()
  43. print(sim.comparisons[(17, 61)])
  44. print(sim.outputs[0][0] * sim.outputs[1][0] * sim.outputs[2][0])