|
| 1 | +//! # Reactor |
| 2 | +use crate::util::hash::*; |
| 3 | + |
| 4 | +pub struct Input<'a> { |
| 5 | + indices: FastMap<&'a str, usize>, |
| 6 | + graph: Vec<Vec<usize>>, |
| 7 | +} |
| 8 | + |
| 9 | +pub fn parse(input: &str) -> Input<'_> { |
| 10 | + let nodes: Vec<Vec<_>> = |
| 11 | + input.lines().map(|line| line.split_ascii_whitespace().collect()).collect(); |
| 12 | + let mut indices = FastMap::new(); |
| 13 | + |
| 14 | + for label in nodes.iter().flatten() { |
| 15 | + let size = indices.len(); |
| 16 | + indices.entry(&label[..3]).or_insert(size); |
| 17 | + } |
| 18 | + |
| 19 | + let mut graph = vec![vec![]; indices.len()]; |
| 20 | + |
| 21 | + for edges in nodes { |
| 22 | + let from = indices[&edges[0][..3]]; |
| 23 | + graph[from].extend(edges[1..].iter().map(|label| indices[label])); |
| 24 | + } |
| 25 | + |
| 26 | + Input { indices, graph } |
| 27 | +} |
| 28 | + |
| 29 | +pub fn part1(input: &Input<'_>) -> u64 { |
| 30 | + paths(input, "you", "out") |
| 31 | +} |
| 32 | + |
| 33 | +pub fn part2(input: &Input<'_>) -> u64 { |
| 34 | + let one = paths(input, "svr", "fft") * paths(input, "fft", "dac") * paths(input, "dac", "out"); |
| 35 | + let two = paths(input, "svr", "dac") * paths(input, "dac", "fft") * paths(input, "fft", "out"); |
| 36 | + one + two |
| 37 | +} |
| 38 | + |
| 39 | +fn paths(input: &Input<'_>, from: &str, to: &str) -> u64 { |
| 40 | + let mut cache = vec![u64::MAX; input.indices.len()]; |
| 41 | + dfs(input, &mut cache, input.indices[from], input.indices[to]) |
| 42 | +} |
| 43 | + |
| 44 | +fn dfs(input: &Input<'_>, cache: &mut [u64], node: usize, end: usize) -> u64 { |
| 45 | + if node == end { |
| 46 | + 1 |
| 47 | + } else if cache[node] == u64::MAX { |
| 48 | + let result = input.graph[node].iter().map(|&next| dfs(input, cache, next, end)).sum(); |
| 49 | + cache[node] = result; |
| 50 | + result |
| 51 | + } else { |
| 52 | + cache[node] |
| 53 | + } |
| 54 | +} |
0 commit comments