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 crate::util::bitset::*;
21use crate::util::grid::*;
22use crate::util::parse::*;
23use std::collections::VecDeque;
24
25type Input = (u16, u16);
26
27pub fn parse(input: &str) -> Input {
28 let grid = Grid::parse(input);
29 let found: Vec<_> =
30 grid.bytes.iter().enumerate().filter(|(_, b)| b.is_ascii_digit()).map(|(i, _)| i).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 = grid.bytes[start].to_decimal() as usize;
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 = grid.bytes[index].to_decimal() as usize;
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 mut table = [[0_u16; 7]; 1 << 7];
83 for k in 0..found.len() - 1 {
84 table[1 << k][k] = distance[0][k + 1];
85 }
86
87 // Visit each non-empty set in order, with no work to do for singleton sets. Start from 3,
88 // since 1 and 2 are singleton sets.
89 for set in 3_usize..(1 << (found.len() - 1)) {
90 if set.is_power_of_two() {
91 continue;
92 }
93
94 // For a given set, compute each g(set,k) for all k in the set.
95 for k in set.biterator() {
96 let subset = set ^ (1 << k);
97 let mut shortest = u16::MAX;
98
99 // For a given destination k, find which other bit m gives the best path from the
100 // subset to m, and then m to k. All table[subset] references were filled in prior
101 // iterations of the outer loop or the singleton base cases.
102 for m in subset.biterator() {
103 shortest = shortest.min(table[subset][m] + distance[m + 1][k + 1]);
104 }
105 table[set][k] = shortest;
106 }
107 }
108
109 // With the sets now built, we have 7 candidates for each answer.
110 let mut part_one = u16::MAX;
111 let mut part_two = u16::MAX;
112 for (k, &path_len) in
113 table[(1 << (found.len() - 1)) - 1].iter().take(found.len() - 1).enumerate()
114 {
115 part_one = part_one.min(path_len);
116 part_two = part_two.min(path_len + distance[k + 1][0]);
117 }
118
119 (part_one, part_two)
120}
121
122pub fn part1(input: &Input) -> u16 {
123 input.0
124}
125
126pub fn part2(input: &Input) -> u16 {
127 input.1
128}