10_bots.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. for line in f:
  15. words = line.split()
  16. if words[0] == 'value':
  17. self.bots[int(words[-1])].append(int(words[1]))
  18. else:
  19. bot = int(words[1])
  20. self.lows[bot] = dests[words[5]], int(words[6])
  21. self.highs[bot] = dests[words[-2]], int(words[-1])
  22. return self
  23. def run(self):
  24. queue = deque(bot for bot, ch in self.bots.items() if len(ch) == 2)
  25. self.comparisons = {}
  26. def give(dest, nr, chip):
  27. dest[nr].append(chip)
  28. if dest == self.bots and len(dest[nr]) == 2:
  29. queue.append(nr)
  30. while queue:
  31. bot = queue.popleft()
  32. chips = self.bots[bot]
  33. if len(chips) == 2:
  34. chips.sort()
  35. self.comparisons[tuple(chips)] = bot
  36. give(*self.highs[bot], chips.pop())
  37. give(*self.lows[bot], chips.pop())
  38. sim = Simulation.parse(sys.stdin)
  39. sim.run()
  40. print(sim.comparisons[(17, 61)])
  41. print(sim.outputs[0][0] * sim.outputs[1][0] * sim.outputs[2][0])