aoc/year2025/day09.rs
1//! # Movie Theater
2use crate::util::iter::*;
3use crate::util::parse::*;
4
5type Tile = [u32; 2];
6
7struct Candidate {
8 x: u32,
9 y: u32,
10 interval: Interval,
11}
12
13/// The set { x in u32 | l <= x <= r }.
14#[derive(Clone, Copy)]
15struct Interval {
16 l: u32,
17 r: u32,
18}
19
20impl Interval {
21 fn new(l: u32, r: u32) -> Self {
22 debug_assert!(l <= r, "interval [{l}, {r}] is empty");
23 Self { l, r }
24 }
25
26 fn intersects(self, other: Self) -> bool {
27 other.l <= self.r && self.l <= other.r
28 }
29
30 fn intersection(self, other: Self) -> Self {
31 debug_assert!(self.intersects(other), "Disjoint intervals have no intersection");
32 Self::new(self.l.max(other.l), self.r.min(other.r))
33 }
34
35 fn contains(self, x: u32) -> bool {
36 self.l <= x && x <= self.r
37 }
38}
39
40pub fn parse(input: &str) -> Vec<Tile> {
41 let mut tiles: Vec<_> = input.iter_unsigned().chunk::<2>().collect();
42 tiles.sort_unstable_by_key(|&[x, y]| (y, x));
43 tiles
44}
45
46pub fn part1(tiles: &[Tile]) -> u64 {
47 let (top_left_tiles, top_right_tiles) = potential_corner_tiles(tiles.iter().copied());
48 let (bottom_left_tiles, bottom_right_tiles) =
49 potential_corner_tiles(tiles.iter().copied().rev());
50
51 find_largest_from_all_corners(&top_left_tiles, &bottom_right_tiles, true)
52 .max(find_largest_from_all_corners(&bottom_left_tiles, &top_right_tiles, false))
53}
54
55pub fn part2(tiles: &[Tile]) -> u64 {
56 // Track the largest area so far during scanning.
57 let mut largest_area = 0;
58
59 // Each red tile (`x`, `y`) becomes a candidate for being a top corner of the largest area, and
60 // during the scan, the `interval` containing the maximum possible width is updated.
61 let mut candidates: Vec<Candidate> = Vec::with_capacity(512);
62
63 // Maintain an ordered list of descending edges, i.e. [begin_interval_0, end_interval_0,
64 // begin_interval_1, end_interval_1, ...].
65 let mut descending_edges = Vec::new();
66
67 // Invariants on the input data (defined by the puzzle) result in points arriving in pairs on
68 // the same y line.
69 for [&[x0, y], &[x1, y1]] in tiles.iter().chunk::<2>() {
70 debug_assert_eq!(y, y1, "red tiles must arrive in pairs on the same row");
71
72 // Update the descending edges. Since we are scanning from top to bottom, and within each
73 // line left to right, when we, starting from outside of the region, hit a corner
74 // tile it is either:
75 //
76 // - The corner of two edges, one going right and one going down. In this case, the
77 // `descending_edges` won't contain the `x` coordinate, and we should "toggle" it on to
78 // denote that there is a new descending edge.
79 // - The corner of two edges, one going right and one going up. The `descending_edges` will
80 // contain an `x` coordinate that should be "toggled" off.
81 //
82 // Similar arguments work for when we are scanning inside the edge and we hit the corner
83 // that ends the edge. This is also why corners always arrive in pairs.
84 //
85 // Do the update.
86 for x in [x0, x1] {
87 toggle_value_membership_in_ordered_list(&mut descending_edges, x);
88 }
89
90 // Check the rectangles this red tile could be a bottom tile for, with the current
91 // candidates.
92 for candidate in &candidates {
93 for x in [x0, x1] {
94 if candidate.interval.contains(x) {
95 largest_area = largest_area.max(
96 (candidate.x.abs_diff(x) + 1) as u64 * (candidate.y.abs_diff(y) + 1) as u64,
97 );
98 }
99 }
100 }
101
102 // Update candidates when their interval shrinks due to descending edge changes, and drop
103 // them when their interval becomes empty.
104 candidates.retain_mut(|candidate| {
105 containing_interval(&descending_edges, candidate.x)
106 .inspect(|i| candidate.interval = i.intersection(candidate.interval))
107 .is_some()
108 });
109
110 // Add any new candidates.
111 for x in [x0, x1] {
112 if let Some(containing) = containing_interval(&descending_edges, x) {
113 candidates.push(Candidate { x, y, interval: containing });
114 }
115 }
116 }
117
118 largest_area
119}
120
121/// This function filters `sorted_tiles` into two lists, one containing all tiles that could be the
122/// top left corner of the largest rectangle (assuming the largest rectangle has a top left corner),
123/// and the second containing all tiles that could be the top right corner.
124///
125/// It assumes `sorted_tiles` is sorted in ascending "y" values, or, to get the top right and bottom
126/// right corners, that `sorted_tiles` is sorted in descending "y" order.
127///
128/// It works (for the top left corners, for illustration) by only returning tiles (from the set of
129/// all tiles, "T") within the region:
130///
131/// R = { (x, y) ∈ ℝ² : ∀ (tx, ty) ∈ T, tx ≤ x ⇒ ty ≥ y }
132///
133/// Tiles outside of this region cannot possibly be a corner of the largest rectangle. Assume, for
134/// proof by contradiction, that the top left corner of the largest rectangle is in the complement
135/// of the set "R":
136///
137/// R' = { (x, y) ∈ ℝ² : ¬ (∀ (tx, ty) ∈ T, tx ≤ x ⇒ ty ≥ y) }
138/// = { (x, y) ∈ ℝ² : ∃ (tx, ty) ∈ T, tx ≤ x ∧ ty < y }
139///
140/// That is, for the corner (x, y), there exists another tile (tx, ty) that is to the left and above
141/// the corner tile, which means the tile isn't the corner of the largest possible rectangle,
142/// completing the proof by contradiction.
143///
144/// The `top_tiles` and `bottom_tiles` are the corner points of this region `R`, built up by
145/// scanning through tiles in either left to right or right to left order.
146///
147/// With just this selection of candidate edge points, the number of points that have to be
148/// compared is already reduced compared to a naive quadratic pairing of all original points.
149/// But exploiting the relationships we just proved above, we can further reduce the comparisons
150/// to O(n log n) by repeatedly picking the mid-point of `top_tiles`, finding which corresponding
151/// point in `bottom_tiles` forms the best rectangle, and then recursively checking just two of the
152/// four combinations of the sublists remaining on either side of the pivots.
153/// [This post](https://codeforces.com/blog/entry/128350) goes more into the theory.
154fn potential_corner_tiles(sorted_tiles: impl Iterator<Item = Tile>) -> (Vec<Tile>, Vec<Tile>) {
155 let mut left_tiles = Vec::new();
156 let mut left_tiles_last_x = u32::MAX;
157
158 let mut right_tiles = Vec::new();
159 let mut right_tiles_last_x = u32::MIN;
160
161 let mut iter = sorted_tiles.peekable();
162
163 while let Some(first_in_row) = iter.next() {
164 let mut last_in_row = first_in_row;
165
166 while let Some(p) = iter.next_if(|p| p[1] == first_in_row[1]) {
167 last_in_row = p;
168 }
169
170 let (y, left_x, right_x) = (
171 first_in_row[1],
172 first_in_row[0].min(last_in_row[0]),
173 first_in_row[0].max(last_in_row[0]),
174 );
175
176 if left_x < left_tiles_last_x {
177 left_tiles.push([left_x, y]);
178 left_tiles_last_x = left_x;
179 }
180
181 if right_x > right_tiles_last_x {
182 right_tiles.push([right_x, y]);
183 right_tiles_last_x = right_x;
184 }
185 }
186
187 right_tiles.reverse();
188 (left_tiles, right_tiles)
189}
190
191#[inline]
192fn find_largest_from_all_corners(corner: &[Tile], opposite_corner: &[Tile], top_left: bool) -> u64 {
193 // Helper struct for a work queue of remaining pairings that need to be checked.
194 struct Work {
195 p_lo: usize,
196 p_hi: usize,
197 q_lo: usize,
198 q_hi: usize,
199 }
200
201 fn add_range(work: &mut Vec<Work>, p_lo: usize, p_hi: usize, q_lo: usize, q_hi: usize) {
202 if p_lo <= p_hi && q_lo <= q_hi {
203 work.push(Work { p_lo, p_hi, q_lo, q_hi });
204 }
205 }
206
207 // Instead of performing an O(n^2) pairing of every point between the two sets, we can
208 // divide and conquer for O(n log n) work by repeatedly dividing the set corner against
209 // the partitions of opposite_corner that correspond to the best result from the halfway
210 // point of corner.
211 let mut largest = 0;
212 let start = Work { p_lo: 0, p_hi: corner.len() - 1, q_lo: 0, q_hi: opposite_corner.len() - 1 };
213 let mut work = vec![start];
214
215 while let Some(job) = work.pop() {
216 // For a given point in corner, sweep the points in opposite_corner to find the
217 // partition point for the best rectangle on the sweep.
218 let p_mid = usize::midpoint(job.p_lo, job.p_hi);
219 let p = corner[p_mid];
220 let mut best_i = None;
221 let mut max_size = 0;
222 let mut q_lim = job.q_lo;
223
224 for (q_i, q) in opposite_corner.iter().enumerate().take(job.q_hi + 1).skip(job.q_lo) {
225 if p[0] > q[0] {
226 q_lim = q_i;
227 } else if (p[1] < q[1]) == top_left {
228 let size = (p[0].abs_diff(q[0]) + 1) as u64 * (p[1].abs_diff(q[1]) + 1) as u64;
229 if size > max_size {
230 max_size = size;
231 best_i = Some(q_i);
232 }
233 }
234 }
235
236 // The sweep determined how to partition smaller searches on the left and right halves.
237 if let Some(i) = best_i {
238 largest = largest.max(max_size);
239 if p_mid > 0 {
240 add_range(&mut work, job.p_lo, p_mid - 1, job.q_lo, i);
241 }
242 add_range(&mut work, p_mid + 1, job.p_hi, i, job.q_hi);
243 } else {
244 if p_mid > 0 && q_lim > 0 {
245 add_range(&mut work, job.p_lo, p_mid - 1, job.q_lo, q_lim - 1);
246 }
247 add_range(&mut work, p_mid + 1, job.p_hi, q_lim, job.q_hi);
248 }
249 }
250
251 largest
252}
253
254// Adds `value` if it isn't in `ordered_list`, removes it if it is, maintaining the order.
255fn toggle_value_membership_in_ordered_list(ordered_list: &mut Vec<u32>, value: u32) {
256 match ordered_list.binary_search(&value) {
257 Ok(i) => {
258 ordered_list.remove(i);
259 }
260 Err(i) => {
261 ordered_list.insert(i, value);
262 }
263 }
264}
265
266// Every pair of descending edges in the ordered list, [begin_interval_0, end_interval_0,
267// begin_interval_1, end_interval_1, ...], defines an interval. Finds the one containing `x`.
268fn containing_interval(descending_edges: &[u32], x: u32) -> Option<Interval> {
269 descending_edges.chunks_exact(2).map(|c| Interval::new(c[0], c[1])).find(|i| i.contains(x))
270}