Files
2026-11-18 21:41:18 +01:00

77 lines
2.2 KiB
Python

import fileinput
from collections import defaultdict
from math import ceil
def parse_graph(inp):
reactions = {}
for line in inp:
# 4 WMVD, 3 PLBT, 1 ZKDMR => 5 CWLGT
inputs, output = line.split(" => ")
inputs = inputs.split(", ")
inputs = [x.split(" ") for x in inputs]
inputs = [(int(x[0]), x[1]) for x in inputs]
output = output.split(" ")
qty, output = (int(output[0]), output[1])
reactions[output] = (qty, tuple(inputs))
return reactions
def topological_sort(graph): # postorder DFS
order = []
def rec(item, visited, order):
if item in visited or item == "ORE":
return
visited.add(item)
_, deps = graph[item]
for _, dep in deps:
rec(dep, visited, order)
order.append(item) # postorder: append item after visiting all its children
rec("FUEL", set(), order)
return order
def find_max_fuel_amount(graph, order, target_ore=1_000_000_000_000):
"""
Find the maximum amount of fuel that can be produced with 1e12 ORE.
Because of waste in batches, ORE(1000 FUEL) < ORE(1 FUEL) * 1000
we must find the smallest n such that ORE(n FUEL) > 1e12 with a binary search.
"""
hi, lo = target_ore, 1
while hi - lo > 1:
mid = (hi + lo) // 2
#print(f"compute_ore_needed({mid}) = {compute_ore_needed(graph, order, mid)}")
if compute_ore_needed(graph, order, mid) > target_ore:
hi = mid
else:
lo = mid
return lo
def compute_ore_needed(graph, order, fuel_amount=1):
"""
Compute the amount of ore needed to produce <fuel_amount> FUEL.
"""
needed = defaultdict(int)
needed["FUEL"] = fuel_amount
for item in reversed(order):
out_qty, deps = graph[item]
batches = ceil(needed[item] / out_qty)
for qty, dep in deps:
needed[dep] += batches * qty
return needed["ORE"]
def main(inp):
graph = parse_graph(inp)
order = topological_sort(graph)
print("Part 1: ", compute_ore_needed(graph, order))
print("Part 2: ", find_max_fuel_amount(graph, order))
if __name__ == '__main__':
with fileinput.input() as f:
lines = [x.rstrip() for x in f]
main(lines)