Browse Source

Solve 2019 day 14

Taddeus Kroes 6 năm trước cách đây
mục cha
commit
87e40f9f62
2 tập tin đã thay đổi với 103 bổ sung0 xóa
  1. 47 0
      2019/14_reactions.py
  2. 56 0
      2019/input/14

+ 47 - 0
2019/14_reactions.py

@@ -0,0 +1,47 @@
+#!/usr/bin/env python3
+import sys
+from collections import defaultdict
+
+def read_graph(f):
+    graph = {'ORE': (1, {})}
+    for line in f:
+        lhs, rhs = line.strip().split(' => ')
+        noutp, outp = rhs.split()
+        assert outp not in graph
+        edges = {}
+        for inp in lhs.split(', '):
+            ninp, inp = inp.split()
+            edges[inp] = int(ninp)
+        graph[outp] = int(noutp), edges
+    return graph
+
+def ore_needed(reactions, fuel):
+    def produce(outp, amount):
+        from_stash = min(amount, stash[outp])
+        stash[outp] -= from_stash
+        amount -= from_stash
+        noutp, inputs = reactions[outp]
+        multiplier = amount // noutp + bool(amount % noutp)
+        for inp, ninp in inputs.items():
+            produce(inp, ninp * multiplier)
+        stash[outp] += noutp * multiplier - amount
+        produced[outp] += amount
+
+    stash = defaultdict(int)
+    produced = defaultdict(int)
+    produce('FUEL', fuel)
+    return produced['ORE']
+
+def fuel_with_ore(reactions, ore):
+    fuel = 0
+    step = ore
+    while step:
+        while ore_needed(reactions, fuel) < ore:
+            fuel += step
+        fuel -= step
+        step //= 2
+    return fuel
+
+reactions = read_graph(sys.stdin)
+print(ore_needed(reactions, 1))
+print(fuel_with_ore(reactions, 1000000000000))

+ 56 - 0
2019/input/14

@@ -0,0 +1,56 @@
+165 ORE => 2 PNBGW
+2 FTZDF, 14 RHWGQ => 8 JTRM
+1 QSKQ, 1 GPRK => 8 HKXF
+2 GKLGP => 3 MTJLK
+4 HXMPQ => 8 VCRLF
+2 DMXC, 2 MTJLK => 8 QSKQ
+39 TCLZ, 17 DKHX, 7 HVPQT, 1 DWMW, 33 THWX, 67 JVGP, 44 RDZSG, 7 JCKT, 22 TDSC, 1 QHVR => 1 FUEL
+6 VCRLF, 1 HXMPQ,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