You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

29 lines
885B

  1. import sys
  2. def game(stack1, stack2, rec=False, N=1):
  3. seen = set()
  4. key = None
  5. while stack1 and stack2:
  6. key = (tuple(stack1), tuple(stack2))
  7. a, b = stack1.pop(), stack2.pop()
  8. if rec and key in seen:
  9. return 0
  10. elif rec and a <= len(stack1) and b <= len(stack2):
  11. p2won = game(stack1[-a:], stack2[-b:], rec=rec, N=N + 1)
  12. else:
  13. p2won = b > a
  14. seen.add(key)
  15. winner = stack2 if p2won else stack1
  16. order = [a, b] if p2won else [b, a]
  17. winner[:] = order + winner
  18. return sum(i * n for i, n in enumerate(winner, 1)) if N == 1 else p2won
  19. text = sys.stdin.read()
  20. p1, p2 = text.split('\n\n')
  21. stack1 = [int(n) for n in p1.splitlines()[1:]][::-1]
  22. stack2 = [int(n) for n in p2.splitlines()[1:]][::-1]
  23. print(game(stack1[:], stack2[:]))
  24. print(game(stack1[:], stack2[:], rec=True))