您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

34 行
937B

  1. import collections
  2. import math
  3. import re
  4. import sys
  5. from toolkit import bsearch
  6. text = sys.stdin.read()
  7. cookbook = {}
  8. for line in text.strip().splitlines():
  9. for i, (qty, name) in enumerate(re.findall(r'(\d+) ([A-Z]+)', line)[::-1]):
  10. if i == 0:
  11. output = name
  12. cookbook[output] = {output: -int(qty)}
  13. else:
  14. cookbook[output][name] = int(qty)
  15. def fuel_to_ore(state):
  16. state = collections.Counter(state)
  17. pending = state.copy()
  18. while pending:
  19. pending = {k: v for k, v in state.items() if k in cookbook and v > 0}
  20. for out, out_qty in pending.items():
  21. min_qty = -cookbook[out][out]
  22. n_times = math.ceil(out_qty / min_qty)
  23. state.update({k: v * n_times for k, v in cookbook[out].items()})
  24. return state
  25. print(fuel_to_ore({'FUEL': 1})['ORE'])
  26. print(bsearch(lambda n: fuel_to_ore({'FUEL': n})['ORE'], 1E12, 1, 10_000_000))