Skip to main content

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