Skip to main content

semi_persistent_egraph/
lca.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Batch LCA queries on the proof forest via Bender–Farach-Colton.
4//!
5//! Two implementations:
6//! - [`LcaTable`]: stores full absolute depths. Simpler, faster queries.
7//! - [`LcaTableCompact`]: stores `i8` deltas + block-start depths instead of
8//!   one absolute depth per tour entry; queries do a short prefix sum.
9//!
10//! Both use O(n) preprocessing. `LcaTable` has O(1) queries;
11//! `LcaTableCompact` reconstructs candidate depths with an O(log n)-length
12//! in-block prefix sum. Both handle forests by introducing a virtual root
13//! that parents all actual roots, preserving the ±1 depth property across
14//! the entire Euler tour.
15//!
16//! # Staleness
17//!
18//! The table is a snapshot of the proof forest at build time. Any subsequent
19//! `union_justified` / `rebuild` calls invalidate it — the caller must
20//! rebuild the table after mutations. This is not enforced by the type system.
21
22use crate::containers::{DenseId, IndexLike};
23
24// ---------------------------------------------------------------------------
25// Shared helpers
26// ---------------------------------------------------------------------------
27
28/// A tour position in `T`'s index word.
29///
30/// # Why `T::Index` is exactly wide enough
31///
32/// The tour has `2*(n + 1) - 1` entries for `n` nodes, so the largest position is `2n`.
33/// For the bit-stealing id families (`Id31`/`Id63`, the only ones a session configures),
34/// the word holds twice the ids: `Index::max_nat() == 2 * id_bound()`. Every node id is
35/// below `id_bound`, so `n <= id_bound` and the largest position `2n` is at most
36/// `Index::max_nat()` — representable, with the stolen bit paying for the doubling. The
37/// tour of a full-capacity proof forest fits in the id's own word and needs nothing
38/// wider, which is why these positions are not `usize`.
39///
40/// Checked rather than cast because that argument is about the id family, and a `T` with
41/// a full-range `Index` (no stolen bit) would not satisfy it. Such a `T` cannot reach
42/// half capacity in memory anyway, so the check never fires; it just refuses to be
43/// silently wrong if one appears.
44#[inline]
45fn tour_pos<T: DenseId>(pos: usize) -> T::Index {
46    <T::Index as IndexLike>::try_from_usize(pos)
47        .expect("Euler tour position exceeds T::Index; configure a wider index word")
48}
49
50/// Virtual-root Euler tour from a proof-parent array.
51/// Returns `(euler, depth, first, tree_id)`.
52/// `euler` and `depth` have length 2*(n+1)-1 (virtual root included).
53/// `first` and `tree_id` have length n+1 (index n = virtual root).
54///
55/// Depths use `usize`, so every forest that can be represented in memory can
56/// also represent its maximum depth. The proof forest is re-rooted around the
57/// original nodes and does not inherit the representative forest's rank bound.
58///
59/// # The unvisited marker in `first`
60///
61/// `first[i] == Index::min()` (zero) means "node `i` has no tour entry yet". Zero is
62/// available as a marker rather than a position because tour position 0 is always the
63/// virtual root's own entry, so no real node's first occurrence can be there — every
64/// `first[i]` this function writes is `>= 1`. The previous marker was `u32::MAX`, which
65/// **is** a reachable position: at full 31-bit capacity the largest position is
66/// `2 * 2^31 == u32::MAX + 1`, so a tour long enough would have written the marker value
67/// into `first` and `lca` would have reported "no such node" for a node that has one.
68fn euler_tour<T: DenseId, const TRACK: bool>(
69    pp: &crate::containers::VecI<T, T::Index, TRACK>,
70    n: usize,
71) -> (Vec<T>, Vec<usize>, Vec<T::Index>, Vec<T::Index>) {
72    let vroot = n;
73    // The virtual root gets its own id, one past the real nodes, so that `lca` can
74    // recognize it in the tour and report "different trees". It used to be *aliased onto
75    // node 0* (`euler.push(T::from_usize(0))` as a "placeholder"), which made the
76    // `result >= n` guard in both `lca` bodies unreachable: a query whose LCA is the
77    // virtual root read back as `Some(node_0)`. Today that range is unreachable for a
78    // second reason — `tree_id` rejects cross-tree pairs before the RMQ runs — so the
79    // guard was a dead fallback that looked live. It is live now.
80    // This also bounds every `T::from_usize` below: `IndexLike::try_from_usize` on a dense
81    // id rejects anything at or past `id_bound()`, so surviving it proves `n` — and therefore
82    // every real node index `< n` — is inside the id space. The masking mint is then exact,
83    // and the check is paid once per tour rather than once per node.
84    let vroot_id = <T as IndexLike>::try_from_usize(n).expect(
85        "proof forest fills the id range, leaving nothing to name the LCA virtual root; \
86         configure a wider id family",
87    );
88    let mut children: Vec<Vec<usize>> = vec![Vec::new(); n + 1];
89    for i in 0..n {
90        let p = pp.get(T::from_usize(i)).to_usize();
91        if p == i {
92            children[vroot].push(i);
93        } else {
94            children[p].push(i);
95        }
96    }
97
98    let cap = 2 * (n + 1);
99    let mut euler = Vec::with_capacity(cap);
100    let mut depth: Vec<usize> = Vec::with_capacity(cap);
101    let unvisited = <T::Index as IndexLike>::min();
102    let mut first = vec![unvisited; n + 1];
103    let mut tree_id = vec![unvisited; n + 1];
104
105    // Single DFS from virtual root
106    // Stack: (node, child_index, depth)
107    let mut stack: Vec<(usize, usize, usize)> = Vec::new();
108    stack.push((vroot, 0, 0));
109    euler.push(vroot_id);
110    depth.push(0);
111    // `first[vroot]` stays at the unvisited marker, which is also its true position (0).
112    // Both readings are unused: `lca` rejects `ai >= n` before touching `first`.
113
114    let mut current_tree = unvisited;
115
116    while let Some((node, ci, d)) = stack.last_mut() {
117        if *ci < children[*node].len() {
118            // The cursor before the bump: `children[vroot]` is filled in ascending node
119            // order, so the k-th descent from the virtual root enters the k-th root and
120            // this ordinal *is* the tree number. The old code recovered it by scanning a
121            // `roots` vector with `position()` — O(roots²) over the build, and an
122            // unchecked `as u32` on the result.
123            let child_ordinal = *ci;
124            let child = children[*node][*ci];
125            *ci += 1;
126            let child_depth = d
127                .checked_add(1)
128                .expect("proof tree depth exceeds addressable memory");
129            // Every entry of `children` is a real node index below `n` (the parent array
130            // has `n` rows), so this is in range without clamping.
131            euler.push(T::from_usize(child));
132            depth.push(child_depth);
133            if first[child] == unvisited {
134                first[child] = tour_pos::<T>(euler.len() - 1);
135            }
136            if *node == vroot {
137                current_tree = tour_pos::<T>(child_ordinal);
138            }
139            tree_id[child] = current_tree;
140            stack.push((child, 0, child_depth));
141        } else {
142            stack.pop();
143            if let Some(&(parent, _, pd)) = stack.last() {
144                euler.push(if parent == vroot {
145                    vroot_id
146                } else {
147                    T::from_usize(parent)
148                });
149                depth.push(pd);
150            }
151        }
152    }
153
154    (euler, depth, first, tree_id)
155}
156
157/// Block decomposition shared state. `I` is the tour-position word (see [`tour_pos`]).
158struct BlockDecomp<I> {
159    block_size: usize,
160    num_blocks: usize,
161    /// Tour position of the minimum-depth entry in each block.
162    block_min: Vec<I>,
163    /// ±1 pattern for each block.
164    block_type: Vec<usize>,
165}
166
167fn block_decompose<T: DenseId>(depth: &[usize], m: usize) -> BlockDecomp<T::Index> {
168    let block_size = ((usize::BITS - m.leading_zeros()) as usize / 2).max(1);
169    let num_blocks = m.div_ceil(block_size);
170
171    let mut block_min = vec![<T::Index as IndexLike>::min(); num_blocks];
172    let mut block_type = vec![0usize; num_blocks];
173
174    for b in 0..num_blocks {
175        let start = b * block_size;
176        let end = (start + block_size).min(m);
177        let mut min_idx = start;
178        let mut min_depth = depth[start];
179        let mut pattern: usize = 0;
180        for i in start..end {
181            if depth[i] < min_depth {
182                min_depth = depth[i];
183                min_idx = i;
184            }
185            if i > start && depth[i] > depth[i - 1] {
186                pattern |= 1 << (i - start - 1);
187            }
188        }
189        block_min[b] = tour_pos::<T>(min_idx);
190        block_type[b] = pattern;
191    }
192
193    BlockDecomp {
194        block_size,
195        num_blocks,
196        block_min,
197        block_type,
198    }
199}
200
201fn build_sparse_table<T: DenseId>(
202    depth: &[usize],
203    bd: &BlockDecomp<T::Index>,
204) -> Vec<Vec<T::Index>> {
205    let num_blocks = bd.num_blocks;
206    let log_blocks = if num_blocks > 1 {
207        (usize::BITS - (num_blocks - 1).leading_zeros()) as usize
208    } else {
209        1
210    };
211    let mut sparse: Vec<Vec<T::Index>> = Vec::with_capacity(log_blocks);
212    sparse.push(bd.block_min.clone());
213
214    for k in 1..log_blocks {
215        let prev = &sparse[k - 1];
216        let half = 1 << (k - 1);
217        let len = num_blocks.saturating_sub(1 << k) + 1;
218        let mut level = Vec::with_capacity(len);
219        for i in 0..len {
220            let left = prev[i];
221            let right = prev[i + half];
222            level.push(if depth[left.as_usize()] <= depth[right.as_usize()] {
223                left
224            } else {
225                right
226            });
227        }
228        sparse.push(level);
229    }
230    sparse
231}
232
233fn build_block_lookup<I>(depth: &[usize], bd: &BlockDecomp<I>, m: usize) -> Vec<Vec<u16>> {
234    let block_size = bd.block_size;
235    let num_patterns = 1usize << block_size.saturating_sub(1);
236    let mut block_lookup: Vec<Vec<u16>> = vec![Vec::new(); num_patterns];
237
238    for b in 0..bd.num_blocks {
239        let bt = bd.block_type[b];
240        if !block_lookup[bt].is_empty() {
241            continue;
242        }
243        let bs = block_size;
244        let base = b * bs;
245        let end = (base + bs).min(m);
246        let mut table = vec![0u16; bs * bs];
247
248        for i in 0..bs {
249            table[i * bs + i] = i as u16;
250            for j in (i + 1)..bs {
251                let prev_min = table[i * bs + j - 1] as usize;
252                table[i * bs + j] = if base + j < end && depth[base + j] < depth[base + prev_min] {
253                    j as u16
254                } else {
255                    prev_min as u16
256                };
257            }
258        }
259        block_lookup[bt] = table;
260    }
261    block_lookup
262}
263
264// ---------------------------------------------------------------------------
265// LcaTable — full depth array
266// ---------------------------------------------------------------------------
267
268/// Precomputed LCA structure with O(1) queries.
269///
270/// Absolute depths use `usize`: proof-edge re-rooting can form a linear chain,
271/// independently of the rank bound on the representative forest.
272pub struct LcaTable<T: DenseId> {
273    euler: Vec<T>,
274    depth: Vec<usize>,
275    /// First tour position of each node, or [`IndexLike::min`] if it has none.
276    first: Vec<T::Index>,
277    tree_id: Vec<T::Index>,
278    n: usize,
279    block_size: usize,
280    sparse: Vec<Vec<T::Index>>,
281    block_lookup: Vec<Vec<u16>>,
282    block_type: Vec<usize>,
283}
284
285impl<T: DenseId> LcaTable<T> {
286    pub fn build<const TRACK: bool>(
287        pp: &crate::containers::VecI<T, T::Index, TRACK>,
288        n: usize,
289    ) -> Self {
290        if n == 0 {
291            return Self {
292                euler: Vec::new(),
293                depth: Vec::new(),
294                first: Vec::new(),
295                tree_id: Vec::new(),
296                n: 0,
297                block_size: 1,
298                sparse: Vec::new(),
299                block_lookup: Vec::new(),
300                block_type: Vec::new(),
301            };
302        }
303
304        let (euler, depth, first, tree_id) = euler_tour(pp, n);
305        let m = euler.len();
306
307        let bd = block_decompose::<T>(&depth, m);
308        let sparse = build_sparse_table::<T>(&depth, &bd);
309        let block_lookup = build_block_lookup(&depth, &bd, m);
310
311        Self {
312            euler,
313            depth,
314            first,
315            tree_id,
316            n,
317            block_size: bd.block_size,
318            sparse,
319            block_lookup,
320            block_type: bd.block_type,
321        }
322    }
323
324    pub fn lca(&self, a: T, b: T) -> Option<T> {
325        let ai = a.to_usize();
326        let bi = b.to_usize();
327        if ai >= self.n || bi >= self.n {
328            return None;
329        }
330        let fa = self.first[ai];
331        let fb = self.first[bi];
332        // `min()` is the "no tour entry" marker, never a real node's first position —
333        // position 0 belongs to the virtual root. See `euler_tour`.
334        let unvisited = <T::Index as IndexLike>::min();
335        if fa == unvisited || fb == unvisited {
336            return None;
337        }
338        if self.tree_id[ai] != self.tree_id[bi] {
339            return None;
340        }
341        let (i, j) = if fa <= fb {
342            (fa.as_usize(), fb.as_usize())
343        } else {
344            (fb.as_usize(), fa.as_usize())
345        };
346        let idx = self.rmq(i, j);
347        let result = self.euler[idx];
348        // If the LCA is the virtual root, nodes are in different trees
349        if result.to_usize() >= self.n {
350            return None;
351        }
352        Some(result)
353    }
354
355    fn rmq(&self, i: usize, j: usize) -> usize {
356        let bi = i / self.block_size;
357        let bj = j / self.block_size;
358
359        if bi == bj {
360            return self.in_block_min(bi, i % self.block_size, j % self.block_size);
361        }
362
363        let left_min = self.in_block_min(bi, i % self.block_size, self.block_size - 1);
364        let right_min = self.in_block_min(bj, 0, j % self.block_size);
365
366        let mut best = if self.depth[left_min] <= self.depth[right_min] {
367            left_min
368        } else {
369            right_min
370        };
371
372        if bi + 1 < bj {
373            let mid_min = self.sparse_query(bi + 1, bj - 1);
374            if self.depth[mid_min] < self.depth[best] {
375                best = mid_min;
376            }
377        }
378
379        best
380    }
381
382    fn sparse_query(&self, bl: usize, br: usize) -> usize {
383        let len = br - bl + 1;
384        let k = (usize::BITS - len.leading_zeros()) as usize - 1;
385        let left = self.sparse[k][bl].as_usize();
386        let right = self.sparse[k][br - (1 << k) + 1].as_usize();
387        if self.depth[left] <= self.depth[right] {
388            left
389        } else {
390            right
391        }
392    }
393
394    fn in_block_min(&self, b: usize, i: usize, j: usize) -> usize {
395        let bt = self.block_type[b];
396        let table = &self.block_lookup[bt];
397        let rel = table[i * self.block_size + j] as usize;
398        b * self.block_size + rel
399    }
400}
401
402// ---------------------------------------------------------------------------
403// LcaTableCompact — delta-encoded depths
404// ---------------------------------------------------------------------------
405
406/// Precomputed LCA structure with delta-encoded depths.
407/// It avoids one absolute-depth word per Euler entry. Queries do a short
408/// prefix sum to recover absolute depths when comparing candidates.
409pub struct LcaTableCompact<T: DenseId> {
410    euler: Vec<T>,
411    /// ±1 deltas between consecutive Euler tour depths. Length = tour_len - 1.
412    delta: Vec<i8>,
413    /// Absolute depth at the start of each block.
414    block_depth: Vec<usize>,
415    /// First tour position of each node, or [`IndexLike::min`] if it has none.
416    first: Vec<T::Index>,
417    tree_id: Vec<T::Index>,
418    n: usize,
419    block_size: usize,
420    /// Sparse table entries: (tour_position, absolute_depth).
421    sparse: Vec<Vec<(T::Index, usize)>>,
422    block_lookup: Vec<Vec<u16>>,
423    block_type: Vec<usize>,
424}
425
426impl<T: DenseId> LcaTableCompact<T> {
427    pub fn build<const TRACK: bool>(
428        pp: &crate::containers::VecI<T, T::Index, TRACK>,
429        n: usize,
430    ) -> Self {
431        if n == 0 {
432            return Self {
433                euler: Vec::new(),
434                delta: Vec::new(),
435                block_depth: Vec::new(),
436                first: Vec::new(),
437                tree_id: Vec::new(),
438                n: 0,
439                block_size: 1,
440                sparse: Vec::new(),
441                block_lookup: Vec::new(),
442                block_type: Vec::new(),
443            };
444        }
445
446        let (euler, depth, first, tree_id) = euler_tour(pp, n);
447        let m = euler.len();
448
449        // Build delta array
450        let mut delta: Vec<i8> = Vec::with_capacity(m.saturating_sub(1));
451        for i in 1..m {
452            let d = match depth[i].cmp(&depth[i - 1]) {
453                std::cmp::Ordering::Greater => 1,
454                std::cmp::Ordering::Less => -1,
455                std::cmp::Ordering::Equal => 0,
456            };
457            debug_assert_eq!(
458                depth[i].abs_diff(depth[i - 1]),
459                1,
460                "±1 property violated at position {i}"
461            );
462            delta.push(d);
463        }
464
465        let bd = block_decompose::<T>(&depth, m);
466
467        // Block-start absolute depths
468        let mut block_depth = Vec::with_capacity(bd.num_blocks);
469        for b in 0..bd.num_blocks {
470            block_depth.push(depth[b * bd.block_size]);
471        }
472
473        // Sparse table storing (position, depth) pairs
474        let sparse = {
475            let num_blocks = bd.num_blocks;
476            let log_blocks = if num_blocks > 1 {
477                (usize::BITS - (num_blocks - 1).leading_zeros()) as usize
478            } else {
479                1
480            };
481            let mut sparse: Vec<Vec<(T::Index, usize)>> = Vec::with_capacity(log_blocks);
482            // Level 0
483            let level0: Vec<(T::Index, usize)> = bd
484                .block_min
485                .iter()
486                .map(|&pos| (pos, depth[pos.as_usize()]))
487                .collect();
488            sparse.push(level0);
489
490            for k in 1..log_blocks {
491                let prev = &sparse[k - 1];
492                let half = 1 << (k - 1);
493                let len = num_blocks.saturating_sub(1 << k) + 1;
494                let mut level = Vec::with_capacity(len);
495                for i in 0..len {
496                    let left = prev[i];
497                    let right = prev[i + half];
498                    level.push(if left.1 <= right.1 { left } else { right });
499                }
500                sparse.push(level);
501            }
502            sparse
503        };
504
505        let block_lookup = build_block_lookup(&depth, &bd, m);
506
507        Self {
508            euler,
509            delta,
510            block_depth,
511            first,
512            tree_id,
513            n,
514            block_size: bd.block_size,
515            sparse,
516            block_lookup,
517            block_type: bd.block_type,
518        }
519    }
520
521    pub fn lca(&self, a: T, b: T) -> Option<T> {
522        let ai = a.to_usize();
523        let bi = b.to_usize();
524        if ai >= self.n || bi >= self.n {
525            return None;
526        }
527        let fa = self.first[ai];
528        let fb = self.first[bi];
529        // `min()` is the "no tour entry" marker, never a real node's first position —
530        // position 0 belongs to the virtual root. See `euler_tour`.
531        let unvisited = <T::Index as IndexLike>::min();
532        if fa == unvisited || fb == unvisited {
533            return None;
534        }
535        if self.tree_id[ai] != self.tree_id[bi] {
536            return None;
537        }
538        let (i, j) = if fa <= fb {
539            (fa.as_usize(), fb.as_usize())
540        } else {
541            (fb.as_usize(), fa.as_usize())
542        };
543        let idx = self.rmq(i, j);
544        let result = self.euler[idx];
545        if result.to_usize() >= self.n {
546            return None;
547        }
548        Some(result)
549    }
550
551    /// Recover absolute depth at tour position `pos` from block-start depth + prefix sum.
552    fn depth_at(&self, pos: usize) -> usize {
553        let b = pos / self.block_size;
554        let offset = pos % self.block_size;
555        let block_start = b * self.block_size;
556        let mut d = self.block_depth[b];
557        for i in block_start..block_start + offset {
558            if self.delta[i] > 0 {
559                d += 1;
560            } else {
561                d = d
562                    .checked_sub(1)
563                    .expect("Euler-tour depth cannot become negative");
564            }
565        }
566        d
567    }
568
569    fn rmq(&self, i: usize, j: usize) -> usize {
570        let bi = i / self.block_size;
571        let bj = j / self.block_size;
572
573        if bi == bj {
574            return self.in_block_min(bi, i % self.block_size, j % self.block_size);
575        }
576
577        let left_pos = self.in_block_min(bi, i % self.block_size, self.block_size - 1);
578        let right_pos = self.in_block_min(bj, 0, j % self.block_size);
579        let left_d = self.depth_at(left_pos);
580        let right_d = self.depth_at(right_pos);
581
582        let (mut best, mut best_d) = if left_d <= right_d {
583            (left_pos, left_d)
584        } else {
585            (right_pos, right_d)
586        };
587
588        if bi + 1 < bj {
589            let (mid_pos, mid_d) = self.sparse_query(bi + 1, bj - 1);
590            if mid_d < best_d {
591                best = mid_pos;
592                best_d = mid_d;
593            }
594        }
595
596        let _ = best_d;
597        best
598    }
599
600    fn sparse_query(&self, bl: usize, br: usize) -> (usize, usize) {
601        let len = br - bl + 1;
602        let k = (usize::BITS - len.leading_zeros()) as usize - 1;
603        let left = self.sparse[k][bl];
604        let right = self.sparse[k][br - (1 << k) + 1];
605        if left.1 <= right.1 {
606            (left.0.as_usize(), left.1)
607        } else {
608            (right.0.as_usize(), right.1)
609        }
610    }
611
612    fn in_block_min(&self, b: usize, i: usize, j: usize) -> usize {
613        let bt = self.block_type[b];
614        let table = &self.block_lookup[bt];
615        let rel = table[i * self.block_size + j] as usize;
616        b * self.block_size + rel
617    }
618}
619
620// ---------------------------------------------------------------------------
621// Tests
622// ---------------------------------------------------------------------------
623
624#[cfg(test)]
625mod tests {
626    use super::*;
627    use crate::containers::VecI;
628    semi_persistent_containers::define_id31! { struct TestId / StoredTestId, "t"; }
629
630    fn make_pp(n: usize, edges: &[(usize, usize)]) -> VecI<TestId, u32, false> {
631        let mut pp = VecI::<TestId, u32, false>::new();
632        for i in 0..n {
633            pp.try_push(TestId::new(i as u32))
634                .expect("push: within index word");
635        }
636        for &(child, parent) in edges {
637            pp.set(TestId::new(child as u32), TestId::new(parent as u32));
638        }
639        pp
640    }
641
642    /// Run the same assertion on both implementations.
643    macro_rules! assert_lca {
644        ($pp:expr, $n:expr, $a:expr, $b:expr, $expected:expr) => {{
645            let table = LcaTable::build(&$pp, $n);
646            let compact = LcaTableCompact::build(&$pp, $n);
647            let a = TestId::new($a);
648            let b = TestId::new($b);
649            let expected: Option<TestId> = $expected.map(TestId::new);
650            assert_eq!(table.lca(a, b), expected, "LcaTable({}, {})", $a, $b);
651            assert_eq!(
652                compact.lca(a, b),
653                expected,
654                "LcaTableCompact({}, {})",
655                $a,
656                $b
657            );
658        }};
659    }
660
661    #[test]
662    fn lca_simple_tree() {
663        //       0
664        //      / \
665        //     1   2
666        //    / \
667        //   3   4
668        let pp = make_pp(5, &[(1, 0), (2, 0), (3, 1), (4, 1)]);
669        assert_lca!(pp, 5, 3, 4, Some(1));
670        assert_lca!(pp, 5, 3, 2, Some(0));
671        assert_lca!(pp, 5, 1, 2, Some(0));
672        assert_lca!(pp, 5, 3, 1, Some(1));
673        assert_lca!(pp, 5, 0, 4, Some(0));
674    }
675
676    #[test]
677    fn lca_chain() {
678        let pp = make_pp(5, &[(1, 0), (2, 1), (3, 2), (4, 3)]);
679        assert_lca!(pp, 5, 0, 4, Some(0));
680        assert_lca!(pp, 5, 2, 4, Some(2));
681        assert_lca!(pp, 5, 3, 3, Some(3));
682    }
683
684    #[test]
685    fn lca_single_node() {
686        let pp = make_pp(1, &[]);
687        assert_lca!(pp, 1, 0, 0, Some(0));
688    }
689
690    #[test]
691    fn lca_two_roots() {
692        let pp = make_pp(4, &[(1, 0), (3, 2)]);
693        assert_lca!(pp, 4, 0, 1, Some(0));
694        assert_lca!(pp, 4, 2, 3, Some(2));
695        assert_lca!(pp, 4, 0, 2, None);
696    }
697
698    #[test]
699    fn lca_wide_tree() {
700        let pp = make_pp(7, &[(1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0)]);
701        for i in 1u32..7 {
702            for j in (i + 1)..7 {
703                assert_lca!(pp, 7, i, j, Some(0));
704            }
705        }
706    }
707
708    #[test]
709    fn lca_larger_tree() {
710        let pp = make_pp(8, &[(1, 0), (2, 0), (3, 1), (4, 1), (5, 2), (6, 2), (7, 3)]);
711        assert_lca!(pp, 8, 7, 4, Some(1));
712        assert_lca!(pp, 8, 7, 5, Some(0));
713        assert_lca!(pp, 8, 5, 6, Some(2));
714        assert_lca!(pp, 8, 7, 3, Some(3));
715        assert_lca!(pp, 8, 3, 6, Some(0));
716    }
717
718    /// Regression: forest with siblings under second root.
719    /// The ±1 property was violated at tree boundaries before the virtual root fix.
720    #[test]
721    fn lca_forest_siblings_under_second_root() {
722        // parents = [0, 0, 2, 2, 2]
723        // tree0 = {0 <- 1}, tree1 = {2 <- 3, 2 <- 4}
724        let pp = make_pp(5, &[(1, 0), (3, 2), (4, 2)]);
725        assert_lca!(pp, 5, 3, 4, Some(2));
726        assert_lca!(pp, 5, 0, 1, Some(0));
727        assert_lca!(pp, 5, 0, 3, None);
728    }
729
730    // --- Proptest -----------------------------------------------------------
731
732    use proptest::prelude::*;
733    use std::collections::HashSet;
734
735    fn forest_strategy(max_n: usize) -> impl Strategy<Value = Vec<usize>> {
736        (2..=max_n).prop_flat_map(|n| {
737            let strats: Vec<_> = (0..n)
738                .map(|i| {
739                    if i == 0 {
740                        Just(0usize).boxed()
741                    } else {
742                        (0..=i).boxed()
743                    }
744                })
745                .collect();
746            strats
747        })
748    }
749
750    fn naive_lca(parents: &[usize], a: usize, b: usize) -> Option<usize> {
751        let n = parents.len();
752        if a >= n || b >= n {
753            return None;
754        }
755        let mut anc_a = HashSet::new();
756        let mut cur = a;
757        loop {
758            anc_a.insert(cur);
759            let p = parents[cur];
760            if p == cur {
761                break;
762            }
763            cur = p;
764        }
765        cur = b;
766        loop {
767            if anc_a.contains(&cur) {
768                return Some(cur);
769            }
770            let p = parents[cur];
771            if p == cur {
772                return if anc_a.contains(&cur) {
773                    Some(cur)
774                } else {
775                    None
776                };
777            }
778            cur = p;
779        }
780    }
781
782    fn pp_from_parents(parents: &[usize]) -> VecI<TestId, u32, false> {
783        let mut pp = VecI::<TestId, u32, false>::new();
784        for &p in parents {
785            pp.try_push(TestId::new(p as u32))
786                .expect("push: within index word");
787        }
788        pp
789    }
790
791    proptest! {
792        #![proptest_config(ProptestConfig::with_cases(5000))]
793
794        #[test]
795        fn prop_lca_matches_naive(
796            parents in forest_strategy(50),
797            a_idx in 0usize..50,
798            b_idx in 0usize..50,
799        ) {
800            let n = parents.len();
801            let a = a_idx % n;
802            let b = b_idx % n;
803
804            let pp = pp_from_parents(&parents);
805            let table = LcaTable::build(&pp, n);
806            let compact = LcaTableCompact::build(&pp, n);
807
808            let expected = naive_lca(&parents, a, b);
809            let full_result = table.lca(TestId::new(a as u32), TestId::new(b as u32))
810                .map(|x| x.to_usize());
811            let compact_result = compact.lca(TestId::new(a as u32), TestId::new(b as u32))
812                .map(|x| x.to_usize());
813
814            prop_assert_eq!(
815                full_result, expected,
816                "LcaTable({}, {}) in {:?}", a, b, parents
817            );
818            prop_assert_eq!(
819                compact_result, expected,
820                "LcaTableCompact({}, {}) in {:?}", a, b, parents
821            );
822        }
823    }
824}