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.

75 satır
1.6KB

  1. from functools import reduce
  2. from itertools import permutations
  3. text = open(0).read()
  4. inp = [eval(line) for line in text.splitlines()]
  5. def explode(state):
  6. last = None
  7. carry = None
  8. def mut(parent, idx, depth=1):
  9. nonlocal last, carry
  10. if type(parent[idx]) == int:
  11. last = parent, idx
  12. if carry:
  13. parent[idx] += carry
  14. raise RuntimeError
  15. elif carry is None and depth == 4:
  16. x, y = parent[idx]
  17. if last:
  18. p, j = last
  19. p[j] += x
  20. carry = y
  21. parent[idx] = 0
  22. else:
  23. mut(parent[idx], 0, depth + 1)
  24. mut(parent[idx], 1, depth + 1)
  25. try:
  26. mut(state, 0)
  27. mut(state, 1)
  28. except RuntimeError:
  29. pass
  30. return carry is not None
  31. def split(state):
  32. def mut(par, idx):
  33. if type(par[idx]) == int:
  34. N = int(par[idx])
  35. if N >= 10:
  36. par[idx] = [N // 2, N // 2 + (N & 1)]
  37. raise RuntimeError
  38. else:
  39. mut(par[idx], 0)
  40. mut(par[idx], 1)
  41. try:
  42. mut(state, 0)
  43. mut(state, 1)
  44. except RuntimeError:
  45. return True
  46. def add(a, b):
  47. state = eval(str([a, b]))
  48. while True:
  49. if explode(state):
  50. continue
  51. elif split(state):
  52. continue
  53. else:
  54. break
  55. return state
  56. def magnitude(seq):
  57. if type(seq) == int:
  58. return seq
  59. x, y = seq
  60. return 3 * magnitude(x) + 2 * magnitude(y)
  61. print(magnitude(reduce(add, inp)))
  62. print(max(magnitude(add(*pair)) for pair in permutations(inp, 2)))