2022 / Day 16
Proboscidea Volcanium
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* The local input is 3639 bytes, 63 lines, longest line 68. There are 63
4 * valves, 15 with positive flow. VALVES = 64, OPEN = 16, MEMO = 524288 (at most
5 * 393216 occupied) and WORK = 4000000 bound BFS distances and exact subset
6 * search. Memoize dominance by opened mask, current valve and remaining
7 * minutes. For the elephant, combine best disjoint masks after subset-max
8 * propagation. */
9
10static slice line(slice s, size_t *p) {
11 size_t b = *p;
12 while (*p < s.l && s.p[*p] != '\n') {
13 (*p)++;
14 }
15 size_t e = *p;
16 if (*p < s.l) {
17 (*p)++;
18 }
19 if (e > b && s.p[e - 1] == '\r') {
20 e--;
21 }
22 return (slice){s.p + b, e - b};
23}
24
25static uint64_t number(slice s, size_t *p, uint64_t limit) {
26 aoc_assert(*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9', "bad number");
27 uint64_t n = 0;
28 while (*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9') {
29 uint64_t d = s.p[(*p)++] - '0';
30 aoc_assert(d <= limit && n <= (limit - d) / 10, "number out of range");
31 n = n * 10 + d;
32 }
33 return n;
34}
35
36static void literal(slice s, size_t *p, const char *t) {
37 size_t n = strlen(t);
38 aoc_assert(*p <= s.l && n <= s.l - *p && memcmp(s.p + *p, t, n) == 0,
39 "bad syntax");
40 *p += n;
41}
42
43enum {
44 VALVES = 64,
45 OPEN = 16,
46 NAMES = 26 * 26,
47 MEMO = 524288,
48 OCCUPIED = 393216,
49 MASKS = 1 << OPEN,
50 WORK = 4000000,
51 RATE = 100000
52};
53
54static int32_t ids[NAMES], rates[VALVES], flow[OPEN], distance[OPEN + 1][OPEN];
55static uint64_t edges[VALVES];
56static uint32_t memo_keys[MEMO];
57static int32_t memo_values[MEMO], best[MASKS];
58static int32_t n, nopen, work, used, answer, elephant;
59
60static int32_t id(slice s, size_t *p) {
61 aoc_assert(*p + 2 <= s.l && s.p[*p] >= 'A' && s.p[*p] <= 'Z' &&
62 s.p[*p + 1] >= 'A' && s.p[*p + 1] <= 'Z',
63 "bad valve name");
64 int32_t name = (s.p[*p] - 'A') * 26 + s.p[*p + 1] - 'A';
65 *p += 2;
66 if (ids[name] < 0) {
67 aoc_assert(n < VALVES, "too many valves");
68 ids[name] = n++;
69 }
70 return ids[name];
71}
72
73static void visit(uint32_t mask, int32_t pos, int32_t time, int32_t score) {
74 aoc_assert(++work <= WORK, "valve search exceeds 4000000 states");
75 if (score > best[mask]) {
76 best[mask] = score;
77 }
78 if (score > answer) {
79 answer = score;
80 }
81 uint32_t key = (mask | ((uint32_t)pos << OPEN) |
82 ((uint32_t)time << (OPEN + 5))) +
83 1,
84 h = (key * 2654435761u) & (MEMO - 1);
85 while (memo_keys[h] && memo_keys[h] != key) {
86 h = (h + 1) & (MEMO - 1);
87 }
88 if (memo_keys[h]) {
89 if (memo_values[h] >= score) {
90 return;
91 }
92 } else {
93 aoc_assert(++used <= OCCUPIED, "valve memo exceeds 393216 states");
94 memo_keys[h] = key;
95 }
96 memo_values[h] = score;
97 for (int32_t i = 0; i < nopen; i++) {
98 if (mask & (1u << i)) {
99 continue;
100 }
101 int32_t left = time - distance[pos][i] - 1;
102 if (left > 0) {
103 visit(mask | (1u << i), i, left, score + flow[i] * left);
104 }
105 }
106}
107
108static inline __attribute__((always_inline)) size_t
109read_valve_neighbors(slice l, size_t q, int32_t v) {
110 while (q < l.l) {
111 int32_t u = id(l, &q);
112 edges[v] |= UINT64_C(1) << u;
113 if (q < l.l) {
114 literal(l, &q, ", ");
115 }
116 }
117
118 return q;
119}
120
121static inline __attribute__((always_inline)) void
122clear_valve_distances(int32_t d[VALVES]) {
123 for (int32_t j = 0; j < n; j++) {
124 d[j] = -1;
125 }
126}
127
128static inline __attribute__((always_inline)) int32_t visit_valve_neighbors(
129 int32_t d[VALVES], int32_t queue[VALVES], int32_t tail, int32_t v) {
130 for (int32_t u = 0; u < n; u++) {
131 if ((edges[v] & (UINT64_C(1) << u)) && d[u] < 0) {
132 d[u] = d[v] + 1;
133 queue[tail++] = u;
134 }
135 }
136
137 return tail;
138}
139
140static inline __attribute__((always_inline)) void
141flood_valve_distances(int32_t d[VALVES], int32_t queue[VALVES],
142 int32_t *head_ref, int32_t *tail_ref) {
143 while ((*head_ref) < (*tail_ref)) {
144 int32_t v = queue[(*head_ref)++];
145 (*tail_ref) = visit_valve_neighbors(d, queue, (*tail_ref), v);
146 }
147}
148
149static inline __attribute__((always_inline)) void
150store_open_valve_distances(int32_t positive[OPEN], int32_t i,
151 int32_t d[VALVES]) {
152 for (int32_t j = 0; j < nopen; j++) {
153 distance[i][j] = d[positive[j]] < 0 ? VALVES : d[positive[j]];
154 }
155}
156
157static inline __attribute__((always_inline)) void
158propagate_best_subsets(int32_t masks, int32_t i) {
159 for (int32_t mask = 0; mask < masks; mask++) {
160 if ((mask & (1 << i)) && best[mask ^ (1 << i)] > best[mask]) {
161 best[mask] = best[mask ^ (1 << i)];
162 }
163 }
164}
165
166static slice solve(slice s, int32_t part) {
167 for (int32_t i = 0; i < NAMES; i++) {
168 ids[i] = -1;
169 }
170 n = nopen = 0;
171 memset(edges, 0, sizeof edges);
172 uint8_t defined[VALVES] = {0};
173 size_t p = 0;
174 while (p < s.l) {
175 slice l = line(s, &p);
176 size_t q = 0;
177 literal(l, &q, "Valve ");
178 int32_t v = id(l, &q);
179 aoc_assert(!defined[v], "duplicate valve definition");
180 defined[v] = 1;
181 literal(l, &q, " has flow rate=");
182 rates[v] = (int32_t)number(l, &q, RATE);
183 if (q + 2 < l.l && l.p[q + 2] == 't' && q + 8 < l.l &&
184 l.p[q + 8] == 's') {
185 literal(l, &q, "; tunnels lead to valves ");
186 } else {
187 literal(l, &q, "; tunnel leads to valve ");
188 }
189 q = read_valve_neighbors(l, q, v);
190 }
191 aoc_assert(n > 0 && ids[0] >= 0, "missing AA valve");
192 int32_t positive[OPEN];
193 for (int32_t i = 0; i < n; i++) {
194 aoc_assert(defined[i], "undefined valve");
195 if (rates[i]) {
196 aoc_assert(nopen < OPEN, "more than 16 positive-flow valves");
197 positive[nopen] = i;
198 flow[nopen++] = rates[i];
199 }
200 }
201 for (int32_t i = 0; i <= nopen; i++) {
202 int32_t d[VALVES], queue[VALVES], head = 0, tail = 0;
203 clear_valve_distances(d);
204 int32_t source = i == nopen ? ids[0] : positive[i];
205 d[source] = 0;
206 queue[tail++] = source;
207 flood_valve_distances(d, queue, &head, &tail);
208 store_open_valve_distances(positive, i, d);
209 }
210 memset(memo_keys, 0, sizeof memo_keys);
211 memset(best, 0, sizeof best);
212 work = used = answer = 0;
213 elephant = part == 2;
214 visit(0, nopen, elephant ? 26 : 30, 0);
215 if (elephant) {
216 int32_t masks = 1 << nopen;
217 for (int32_t i = 0; i < nopen; i++) {
218 propagate_best_subsets(masks, i);
219 }
220 answer = 0;
221 for (int32_t mask = 0; mask < masks; mask++) {
222 int32_t sum = best[mask] + best[(masks - 1) ^ mask];
223 if (sum > answer) {
224 answer = sum;
225 }
226 }
227 }
228 return slice_from_i64(answer);
229}
230
231slice part1(slice s) {
232 return solve(s, 1);
233}
234
235slice part2(slice s) {
236 return solve(s, 2);
237}
238
239const struct aoc_method aoc_methods[] = {{0, 0}};aoc.h
1#ifndef AOC_H
2#define AOC_H
3
4#include <stdarg.h>
5#include <stddef.h>
6#include <stdint.h>
7#include <stdlib.h>
8#include <string.h>
9
10/* The only required boundary between infra and a solution.
11 * `input` is read-only and is not owned by the solution.
12 * The returned slice is allocated with malloc. It is the only
13 * block still live when the function returns. Infra copies it
14 * and then frees it.
15 */
16typedef struct {
17 uint8_t *p;
18 size_t l;
19} slice;
20
21/* p is null and l is 0. Infra uses this when a run has no output. */
22static const slice empty_slice = {0};
23
24typedef slice (*aoc_fn)(slice);
25
26/* One named method. The name is a C identifier, at most 31
27 * characters, and it is the URL suffix: /YYYY/D/P/<name>.
28 * estimate and span are examples, not a fixed list. A day
29 * exports as many as it wants. The array ends with {0, 0}.
30 * part1 and part2 are not entries in this list.
31 */
32struct aoc_method {
33 const char *name;
34 aoc_fn fn;
35};
36
37slice part1(slice input);
38slice part2(slice input);
39
40extern const struct aoc_method aoc_methods[];
41
42/* Provided by the runtime. Records msg and returns. */
43void aoc_fail(const char *msg);
44
45/* Stops the run when cond is false and reports msg. */
46_Noreturn void aoc_assert_fail(const char *msg);
47#ifndef aoc_assert
48#define aoc_assert(cond, msg) \
49 do { \
50 if (!(cond)) { \
51 aoc_assert_fail(msg); \
52 } \
53 } while (0)
54#endif
55
56/* Decimal text of a uint64_t is at most 20 digits. A sign and a
57 * little spare fit here. Size a number buffer from this.
58 */
59enum { AOC_I64_TEXT = 32 };
60
61/* Decimal digits of v. No sign. d has room for 20 digits. */
62static inline char *aoc_u64_text(char *d, uint64_t v) {
63 char tmp[AOC_I64_TEXT];
64 char *end = tmp + AOC_I64_TEXT;
65 char *p = end;
66 size_t n;
67 do {
68 *--p = (char)('0' + (v % 10ull));
69 v /= 10ull;
70 } while (v);
71 n = (size_t)(end - p);
72 memcpy(d, p, n);
73 return d + n;
74}
75
76/* Decimal digits of v. The minimum int64_t is not negated. */
77static inline char *aoc_i64_text(char *d, int64_t v) {
78 uint64_t u;
79 if (v < 0) {
80 *d++ = '-';
81 u = (uint64_t)(-(v + 1)) + 1ull;
82 } else {
83 u = (uint64_t)v;
84 }
85 return aoc_u64_text(d, u);
86}
87
88/* n values, one space between them. The author knows the order. */
89static inline char *aoc_u64s(char *d, const uint64_t *v, size_t n) {
90 size_t i;
91 for (i = 0; i < n; i++) {
92 if (i) {
93 *d++ = ' ';
94 }
95 d = aoc_u64_text(d, v[i]);
96 }
97 return d;
98}
99
100static inline char *aoc_i64s(char *d, const int64_t *v, size_t n) {
101 size_t i;
102 for (i = 0; i < n; i++) {
103 if (i) {
104 *d++ = ' ';
105 }
106 d = aoc_i64_text(d, v[i]);
107 }
108 return d;
109}
110
111static inline char *aoc_ints(char *d, const int *v, size_t n) {
112 size_t i;
113 for (i = 0; i < n; i++) {
114 if (i) {
115 *d++ = ' ';
116 }
117 d = aoc_i64_text(d, (int64_t)v[i]);
118 }
119 return d;
120}
121
122/* Write fmt at buf. Return the cursor for the next call.
123 * %d takes int. %i takes int64_t. %u takes uint64_t.
124 * %s takes a C string. %% is a percent sign.
125 * A literal run is memcpy.
126 * %D takes (int *, size_t). %I takes (int64_t *, size_t).
127 * %U takes (uint64_t *, size_t). One space between values.
128 */
129static inline char *aoc_vprintf(const char *fmt, char *buf, va_list ap) {
130 while (*fmt) {
131 const char *lit = fmt;
132 size_t n;
133 while (*fmt && *fmt != '%') {
134 fmt++;
135 }
136 n = (size_t)(fmt - lit);
137 if (n) {
138 memcpy(buf, lit, n);
139 buf += n;
140 }
141 if (*fmt != '%') {
142 break;
143 }
144 fmt++;
145 if (*fmt == '%') {
146 *buf++ = '%';
147 fmt++;
148 continue;
149 }
150 if (*fmt == 's') {
151 const char *s = va_arg(ap, const char *);
152 n = strlen(s);
153 if (n) {
154 memcpy(buf, s, n);
155 buf += n;
156 }
157 fmt++;
158 continue;
159 }
160 if (*fmt == 'd') {
161 buf = aoc_i64_text(buf, (int64_t)va_arg(ap, int));
162 fmt++;
163 continue;
164 }
165 if (*fmt == 'i') {
166 buf = aoc_i64_text(buf, va_arg(ap, int64_t));
167 fmt++;
168 continue;
169 }
170 if (*fmt == 'u') {
171 buf = aoc_u64_text(buf, va_arg(ap, uint64_t));
172 fmt++;
173 continue;
174 }
175 if (*fmt == 'D') {
176 const int *v = va_arg(ap, int *);
177 buf = aoc_ints(buf, v, va_arg(ap, size_t));
178 fmt++;
179 continue;
180 }
181 if (*fmt == 'I') {
182 const int64_t *v = va_arg(ap, int64_t *);
183 buf = aoc_i64s(buf, v, va_arg(ap, size_t));
184 fmt++;
185 continue;
186 }
187 if (*fmt == 'U') {
188 const uint64_t *v = va_arg(ap, uint64_t *);
189 buf = aoc_u64s(buf, v, va_arg(ap, size_t));
190 fmt++;
191 continue;
192 }
193 aoc_assert(0, "bad format");
194 }
195 return buf;
196}
197
198static inline char *aoc_printf(const char *fmt, char *buf, ...) {
199 va_list ap;
200 va_start(ap, buf);
201 buf = aoc_vprintf(fmt, buf, ap);
202 va_end(ap);
203 return buf;
204}
205
206/* Copy n bytes of text into a malloc'd slice. */
207static inline slice slice_from_text(const char *s, size_t n) {
208 uint8_t *p = malloc(n);
209 aoc_assert(p, "out of memory");
210 if (n) {
211 memcpy(p, s, n);
212 }
213 return (slice){p, n};
214}
215
216/* Decimal text of v, allocated at AOC_I64_TEXT. The minimum
217 * int64_t is not negated. slice.l is the bytes written.
218 */
219static inline slice slice_from_i64(int64_t v) {
220 char tmp[AOC_I64_TEXT];
221 char *d;
222 uint8_t *p;
223 size_t n;
224 d = aoc_printf("%i", tmp, v);
225 n = (size_t)(d - tmp);
226 p = malloc(AOC_I64_TEXT);
227 aoc_assert(p, "out of memory");
228 memcpy(p, tmp, n);
229 return (slice){p, n};
230}
231
232/* Parse one decimal slice into *out. A leading '-' is allowed.
233 * Returns 1 on success, 0 for invalid text or int64_t overflow.
234 */
235static inline int slice_to_i64(slice s, int64_t *out) {
236 size_t i = 0;
237 int neg = 0;
238 uint64_t u = 0;
239 if (!s.p || s.l == 0 || !out) {
240 return 0;
241 }
242 if (s.p[0] == '-') {
243 neg = 1;
244 i = 1;
245 if (s.l == 1) {
246 return 0;
247 }
248 }
249 for (; i < s.l; i++) {
250 uint8_t c = s.p[i];
251 if (c < '0' || c > '9') {
252 return 0;
253 }
254 uint64_t digit = (uint64_t)(c - '0');
255 uint64_t limit = (uint64_t)INT64_MAX + (uint64_t)neg;
256 if (u > (limit - digit) / 10u) {
257 return 0;
258 }
259 u = u * 10u + digit;
260 }
261 if (neg) {
262 *out = u == (uint64_t)INT64_MAX + 1u ? INT64_MIN : -(int64_t)u;
263 } else {
264 *out = (int64_t)u;
265 }
266 return 1;
267}
268
269#endifThe aha moment
The volcano gives us thirty minutes and 63 valves connected by 152 directed tunnel entries. It is tempting to chase the largest flow rate first. But a distant valve may spend most of the deadline unopened, while a modest nearby valve can release pressure for many minutes. The decision is about flow multiplied by useful time, and opening one valve changes where we begin the next trip.
Before searching minute-by-minute actions, inspect the rates. Only fifteen valves have positive flow, ranging from 3 to 25. The other 48 still matter as passages, but opening them cannot help. This is the first reduction: the meaningful choices are which useful valve to open next, not which tunnel to walk through every minute.
Run BFS from AA and each useful valve to obtain shortest travel distances through the full graph. Every tunnel costs one minute, so an ordinary queue suffices. Once the next valve is chosen, a longer route cannot improve anything: it opens the same valve later and leaves less time for every continuation. We can jump directly between useful decisions, charging shortest travel time plus one minute to open the valve.
If that leaves t minutes and the valve's rate is r, credit r × t immediately. That amount is its entire eventual contribution, including pressure released while we travel elsewhere. We no longer need to update a running flow total once per minute. The local useful-to-useful distances are at most twelve, so many ambitious sequences run out of time quickly.
Fifteen useful valves still have about 1.3 trillion complete orderings. Time rules out most, but repeated situations provide another reduction. A situation is the current valve, remaining time, and set of opened valves. If we reach that same situation with less pressure credited, the better arrival can take every continuation we could take. Discard the worse one. A fifteen-bit mask records the opened set exactly. The local thirty-minute search makes 117,624 visits and stores 57,962 distinct situations—small enough for a direct recursive search with this dominance table.
Part two hands us an elephant and takes four minutes away. Searching both travelers' actions together sounds unpleasant: who moves first, who waits, who opens what? Read the interaction rules carefully. We can share tunnels and pass each other freely. The only scarce resource is a valve: opening it twice earns nothing.
Aha, coordinate the division of work rather than the minute-by-minute movements. Run the one-traveler search for 26 minutes and record the best pressure for each exactly opened mask. Here it visits 28,122 situations in total and reaches 4,457 different masks. Any two routes with disjoint masks can run concurrently; their pressure contributions add.
There are 32,768 possible masks. For each allowed set, we want the best route that opens any subset of it, since the deadline may prevent opening every assigned valve. Propagate each mask's best value from the masks obtained by removing one bit. Across fifteen bits this takes 245,760 comparisons. Then try every partition: our allowed mask and the elephant's complementary mask. Their best subset scores give the best compatible pair. A valve may remain unopened, and the two routes need not have equal lengths or equal numbers of valves.
The implementation accepts 64 total valves, sixteen with positive flow, and rates through 100,000. It bounds search at four million visits and 393,216 distinct memo states. The breakthrough is a succession of precise questions: which rooms contain decisions, what makes two partial plans equivalent, and what do the two workers actually compete for? Those answers turn a frantic joint simulation into a manageable search over subsets.
See also
Categories for 2015–2024 adapted from u/Boojum’s 500 Stars: A Categorization and Mega-Guide ↗. A day can belong to several categories. Tags from 2025 onward are our additions.
Try your input
One POST, one reply. Your input is not saved.