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