Skip to main content

aoc/year2016/
day24.rs

1//! # Air Duct Spelunking
2//!
3//! This is a variant of the classic [Travelling Salesman Problem] and is similar to
4//! [`Year 2015 Day 13`].
5//!
6//! We first simplify the problem by finding the distance between all locations using multiple
7//! [BFS](https://en.wikipedia.org/wiki/Breadth-first_search)
8//! searches starting from each location.
9//!
10//! Then we can use [Held-Karp's dynamic programming][Held-Karp] algorithm to determine the
11//! shortest cycle. The problem asks us to start from node 0, which conveniently means that the
12//! value g(127, k) is the shortest path to k, and adding the distance from k back to 0 for part 2
13//! is also trivial. Thus, this day completes with only `7*6/2*128/2` or 1,344 comparisons, quite a
14//! bit better than the 2,520 comparisons needed for an approach with 7!/2 permutations. A
15//! slight complication is that set bit 0 maps to node 1.
16//!
17//! [`Year 2015 Day 13`]: crate::year2015::day13
18//! [Travelling Salesman Problem]: https://en.wikipedia.org/wiki/Travelling_salesman_problem
19//! [Held-Karp]: https://en.wikipedia.org/wiki/Held%E2%80%93Karp_algorithm
20use std::collections::VecDeque;
21
22use crate::util::bitset::*;
23use crate::util::grid::*;
24use crate::util::parse::*;
25
26type Input = (u16, u16);
27
28pub fn parse(input: &str) -> Input {
29    let grid = Grid::parse(input);
30    let found: Vec<_> = (0..grid.bytes.len()).filter(|&i| grid.bytes[i].is_ascii_digit()).collect();
31
32    let width = grid.width as isize;
33    // There are 8 locations.
34    let mut distance = [[0; 8]; 8];
35
36    // BFS from each location. As minor optimizations we reuse `todo` and `seen`,
37    // and short-circuit each BFS once it will not learn anything new.
38    let mut todo = VecDeque::new();
39    let mut seen = vec![0; grid.bytes.len()];
40
41    for (rank, &start) in found.iter().skip(1).enumerate() {
42        let from: usize = grid.bytes[start].to_decimal();
43        let mut need = found.len() - rank;
44
45        todo.clear();
46        todo.push_back((start, 0));
47        seen[start] = start;
48
49        while let Some((index, steps)) = todo.pop_front() {
50            if grid.bytes[index].is_ascii_digit() {
51                let to: usize = grid.bytes[index].to_decimal();
52                if distance[from][to] == 0 {
53                    distance[from][to] = steps;
54                    distance[to][from] = steps;
55                    need -= 1;
56                    // Short-circuit once we've found all needed pairs.
57                    if need == 0 {
58                        break;
59                    }
60                }
61            }
62
63            // All interesting points (digits and junctions) are at odd locations,
64            // so we step by 2 spaces in each direction.
65            for delta in [1, -1, width, -width] {
66                let first = index.wrapping_add_signed(delta);
67                if grid.bytes[first] != b'#' {
68                    let second = index.wrapping_add_signed(2 * delta);
69                    if seen[second] != start {
70                        seen[second] = start;
71                        todo.push_back((second, steps + 2));
72                    }
73                }
74            }
75        }
76    }
77
78    // Solve both parts simultaneously.
79    // Initialize a table for each part: 2ⁿ⁻¹ sets with n-1 distances per set. Default each g({k},k)
80    // singleton to distance[0][k+1] (since bit 0 maps to node 1), while the initial value of other
81    // sets does not matter.
82    let others = found.len() - 1;
83    let mut table = [[0; 7]; 1 << 7];
84
85    // Visit each non-empty set in order.
86    for set in 1_usize..(1 << others) {
87        // For a given set, compute each g(set,k) for all k in the set.
88        for k in set.biterator() {
89            let subset = set ^ (1 << k);
90
91            // For a given destination k, find which other bit m gives the best path from the
92            // subset to m, and then m to k. All table[subset] references were filled in prior
93            // iterations of the outer loop. Singleton sets have an empty subset, so g({k},k) is
94            // the distance from node 0 to node k+1.
95            table[set][k] = subset
96                .biterator()
97                .map(|m| table[subset][m] + distance[m + 1][k + 1])
98                .min()
99                .unwrap_or(distance[0][k + 1]);
100        }
101    }
102
103    // With the sets now built, we have 7 candidates for each answer.
104    let mut part_one = u16::MAX;
105    let mut part_two = u16::MAX;
106
107    for (k, &path_len) in table[(1 << others) - 1].iter().take(others).enumerate() {
108        part_one = part_one.min(path_len);
109        part_two = part_two.min(path_len + distance[k + 1][0]);
110    }
111
112    (part_one, part_two)
113}
114
115pub fn part1(input: &Input) -> u16 {
116    input.0
117}
118
119pub fn part2(input: &Input) -> u16 {
120    input.1
121}