1use crate::util::hash::*;
6use crate::util::iter::*;
7use crate::util::parse::*;
8
9struct Ingredient {
10 amount: u64,
11 chemical: usize,
12}
13
14pub struct Reaction {
15 amount: u64,
16 chemical: usize,
17 ingredients: Vec<Ingredient>,
18}
19
20pub fn parse(input: &str) -> Vec<Reaction> {
23 let lines: Vec<_> = input.lines().collect();
24
25 let mut reactions = Vec::from_fn(lines.len() + 1, |chemical| Reaction {
27 amount: 0,
28 chemical,
29 ingredients: Vec::new(),
30 });
31
32 let mut indices = FastMap::build([("FUEL", 0), ("ORE", 1)]);
34
35 let mut lookup = |s| {
36 let size = indices.len();
37 *indices.entry(s).or_insert(size)
38 };
39
40 for line in lines {
41 let mut tokens = line
42 .rsplit(|c: char| !c.is_ascii_alphanumeric())
43 .filter(|s| !s.is_empty())
44 .chunk::<2>();
45
46 let [kind, amount] = tokens.next().unwrap();
48 let chemical = lookup(kind);
49
50 let reaction = &mut reactions[chemical];
51 reaction.amount = amount.unsigned();
52
53 for [kind, amount] in tokens {
54 let chemical = lookup(kind);
55 reaction.ingredients.push(Ingredient { amount: amount.unsigned(), chemical });
56 }
57 }
58
59 let mut order = vec![0; reactions.len()];
61 topological(&reactions, &mut order, 0, 0);
62 reactions.sort_unstable_by_key(|r| order[r.chemical]);
63 reactions
64}
65
66pub fn part1(input: &[Reaction]) -> u64 {
69 ore(input, 1)
70}
71
72pub fn part2(input: &[Reaction]) -> u64 {
74 let threshold = 1_000_000_000_000;
75 let mut start = 1_u64;
76 let mut end = threshold;
77
78 while start != end {
79 let middle = (start + end).div_ceil(2);
80
81 if ore(input, middle) > threshold {
82 end = middle - 1;
83 } else {
84 start = middle;
85 }
86 }
87
88 start
89}
90
91fn topological(reactions: &[Reaction], order: &mut [usize], chemical: usize, depth: usize) {
94 order[chemical] = order[chemical].max(depth);
95
96 for ingredient in &reactions[chemical].ingredients {
97 topological(reactions, order, ingredient.chemical, depth + 1);
98 }
99}
100
101fn ore(reactions: &[Reaction], amount: u64) -> u64 {
104 let mut total = vec![0; reactions.len()];
105 total[0] = amount;
106
107 for reaction in &reactions[..reactions.len() - 1] {
108 let multiplier = total[reaction.chemical].div_ceil(reaction.amount);
109
110 for ingredient in &reaction.ingredients {
111 total[ingredient.chemical] += multiplier * ingredient.amount;
112 }
113 }
114
115 total[1]
116}