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<_> =
31        grid.bytes.iter().enumerate().filter(|(_, b)| b.is_ascii_digit()).map(|(i, _)| i).collect();
32
33    let width = grid.width as isize;
34    // There are 8 locations.
35    let mut distance = [[0; 8]; 8];
36
37    // BFS from each location. As minor optimizations we reuse `todo` and `seen`,
38    // and short-circuit each BFS once it will not learn anything new.
39    let mut todo = VecDeque::new();
40    let mut seen = vec![0; grid.bytes.len()];
41
42    for (rank, &start) in found.iter().skip(1).enumerate() {
43        let from: usize = grid.bytes[start].to_decimal();
44        let mut need = found.len() - rank;
45
46        todo.clear();
47        todo.push_back((start, 0));
48        seen[start] = start;
49
50        while let Some((index, steps)) = todo.pop_front() {
51            if grid.bytes[index].is_ascii_digit() {
52                let to: usize = grid.bytes[index].to_decimal();
53                if distance[from][to] == 0 {
54                    distance[from][to] = steps;
55                    distance[to][from] = steps;
56                    need -= 1;
57                    // Short-circuit once we've found all needed pairs.
58                    if need == 0 {
59                        break;
60                    }
61                }
62            }
63
64            // All interesting points (digits and junctions) are at odd locations,
65            // so we step by 2 spaces in each direction.
66            for delta in [1, -1, width, -width] {
67                let first = index.wrapping_add_signed(delta);
68                if grid.bytes[first] != b'#' {
69                    let second = index.wrapping_add_signed(2 * delta);
70                    if seen[second] != start {
71                        seen[second] = start;
72                        todo.push_back((second, steps + 2));
73                    }
74                }
75            }
76        }
77    }
78
79    // Solve both parts simultaneously.
80    // Initialize a table for each part: 2ⁿ⁻¹ sets with n-1 distances per set. Default each g({k},k)
81    // singleton to distance[0][k+1] (since bit 0 maps to node 1), while the initial value of other
82    // sets does not matter.
83    let mut table = [[0_u16; 7]; 1 << 7];
84    for k in 0..found.len() - 1 {
85        table[1 << k][k] = distance[0][k + 1];
86    }
87
88    // Visit each non-empty set in order, with no work to do for singleton sets. Start from 3,
89    // since 1 and 2 are singleton sets.
90    for set in 3_usize..(1 << (found.len() - 1)) {
91        if set.is_power_of_two() {
92            continue;
93        }
94
95        // For a given set, compute each g(set,k) for all k in the set.
96        for k in set.biterator() {
97            let subset = set ^ (1 << k);
98            let mut shortest = u16::MAX;
99
100            // For a given destination k, find which other bit m gives the best path from the
101            // subset to m, and then m to k. All table[subset] references were filled in prior
102            // iterations of the outer loop or the singleton base cases.
103            for m in subset.biterator() {
104                shortest = shortest.min(table[subset][m] + distance[m + 1][k + 1]);
105            }
106            table[set][k] = shortest;
107        }
108    }
109
110    // With the sets now built, we have 7 candidates for each answer.
111    let mut part_one = u16::MAX;
112    let mut part_two = u16::MAX;
113    for (k, &path_len) in
114        table[(1 << (found.len() - 1)) - 1].iter().take(found.len() - 1).enumerate()
115    {
116        part_one = part_one.min(path_len);
117        part_two = part_two.min(path_len + distance[k + 1][0]);
118    }
119
120    (part_one, part_two)
121}
122
123pub fn part1(input: &Input) -> u16 {
124    input.0
125}
126
127pub fn part2(input: &Input) -> u16 {
128    input.1
129}