Skip to main content

devpage_design/prefix_sums/
mod.rs

1//! A sequence in key order that knows the summary of every prefix in log
2//! time: a treap whose every node holds the summary of its subtree. What a
3//! run keeps its children's sizes in, so a child's change of size, an insert
4//! before the first of 100,000 or a search for the child at a place along
5//! the run costs log time, and moves no sibling.
6
7use std::cmp::Ordering;
8
9/// What a stretch of items adds up to: `then` is the stretch followed by
10/// `next`, and `Default` is the empty stretch.
11pub trait Summary: Clone + Default {
12    /// The summary of this stretch followed by `next`.
13    fn then(&self, next: &Self) -> Self;
14}
15
16/// An item of a [`Sums`] and what it adds up to by itself.
17pub trait Item {
18    type Sum: Summary;
19    /// What the item adds up to by itself.
20    fn summary(&self) -> Self::Sum;
21}
22
23/// A node's index in the arena; `None` for an empty subtree.
24type Link = Option<u32>;
25
26/// One item of the treap, and the summary and size of the subtree it roots.
27struct Node<K, V: Item> {
28    /// The item's key, which orders the tree.
29    key: K,
30    /// The item stored under `key`; its summary is folded into `sum`.
31    value: V,
32    /// The node's heap priority: a parent's is greater than its children's.
33    priority: u64,
34    /// The subtree of keys before this one.
35    left: Link,
36    /// The subtree of keys after this one.
37    right: Link,
38    /// The summary of this subtree, in key order.
39    sum: V::Sum,
40    /// How many items this subtree holds.
41    count: usize,
42}
43
44/// Items by key, each prefix's summary in log time.
45pub struct Sums<K, V: Item> {
46    /// The arena every node lives in, by index; `None` at a freed slot.
47    nodes: Vec<Option<Node<K, V>>>,
48    /// The freed slots of `nodes`, reused before the arena grows.
49    free: Vec<u32>,
50    /// The root of the tree; `None` when it holds no items.
51    root: Link,
52    /// The state of the generator that draws each new node's priority.
53    seed: u64,
54}
55
56impl<K: Ord + Clone, V: Item> Default for Sums<K, V> {
57    fn default() -> Self {
58        Sums::new()
59    }
60}
61
62impl<K: Ord + Clone, V: Item> Sums<K, V> {
63    /// No items.
64    pub fn new() -> Self {
65        Sums {
66            nodes: Vec::new(),
67            free: Vec::new(),
68            root: None,
69            seed: 0x9e37_79b9_7f4a_7c15,
70        }
71    }
72
73    /// How many items there are.
74    pub fn len(&self) -> usize {
75        self.root.map_or(0, |r| self.node(r).count)
76    }
77
78    /// Whether there are no items.
79    pub fn is_empty(&self) -> bool {
80        self.root.is_none()
81    }
82
83    /// The summary of every item.
84    pub fn total(&self) -> V::Sum {
85        self.sum(self.root)
86    }
87
88    /// The item at `key`; `None` when there is none.
89    pub fn get(&self, key: &K) -> Option<&V> {
90        let mut at = self.root;
91        while let Some(i) = at {
92            let n = self.node(i);
93            at = match key.cmp(&n.key) {
94                Ordering::Less => n.left,
95                Ordering::Greater => n.right,
96                Ordering::Equal => return Some(&n.value),
97            };
98        }
99        None
100    }
101
102    /// Puts `value` at `key`, replacing what was there; returns it.
103    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
104        let old = self.remove(&key);
105        let (l, r) = self.split(self.root, &key, false);
106        let priority = self.next_priority();
107        let sum = value.summary();
108        let n = self.alloc(Node {
109            key,
110            value,
111            priority,
112            left: None,
113            right: None,
114            sum,
115            count: 1,
116        });
117        let m = self.merge(l, Some(n));
118        self.root = self.merge(m, r);
119        old
120    }
121
122    /// Takes the item at `key` out.
123    pub fn remove(&mut self, key: &K) -> Option<V> {
124        let (l, r) = self.split(self.root, key, false);
125        let (m, r) = self.split(r, key, true);
126        self.root = self.merge(l, r);
127        let m = m?;
128        let node = self.nodes[m as usize].take().expect("a live node");
129        self.free.push(m);
130        Some(node.value)
131    }
132
133    /// The summary of every item before `key`.
134    pub fn before(&self, key: &K) -> V::Sum {
135        let mut acc = V::Sum::default();
136        let mut at = self.root;
137        while let Some(i) = at {
138            let n = self.node(i);
139            if *key <= n.key {
140                at = n.left;
141            } else {
142                acc = acc.then(&self.sum(n.left)).then(&n.value.summary());
143                at = n.right;
144            }
145        }
146        acc
147    }
148
149    /// The first item whose prefix — the summary of it and everything before
150    /// it — `reaches`, which must be false and then true along the items;
151    /// with the summary of everything before it.
152    pub fn seek(&self, reaches: impl Fn(&V::Sum) -> bool) -> Option<(&K, &V, V::Sum)> {
153        let mut acc = V::Sum::default();
154        let mut at = self.root;
155        let mut found = None;
156        while let Some(i) = at {
157            let n = self.node(i);
158            let left = acc.then(&self.sum(n.left));
159            let with = left.then(&n.value.summary());
160            if reaches(&with) {
161                found = Some((&n.key, &n.value, left.clone()));
162                at = n.left;
163            } else {
164                acc = with;
165                at = n.right;
166            }
167        }
168        found
169    }
170
171    /// The items from `key` on, in order.
172    pub fn from<'a>(&'a self, key: &K) -> impl Iterator<Item = (&'a K, &'a V)> + 'a {
173        let mut stack = Vec::new();
174        let mut at = self.root;
175        while let Some(i) = at {
176            let n = self.node(i);
177            if n.key >= *key {
178                stack.push(i);
179                at = n.left;
180            } else {
181                at = n.right;
182            }
183        }
184        Walk { sums: self, stack }
185    }
186
187    /// Every item, in order.
188    pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> {
189        let mut stack = Vec::new();
190        let mut at = self.root;
191        while let Some(i) = at {
192            stack.push(i);
193            at = self.node(i).left;
194        }
195        Walk { sums: self, stack }
196    }
197
198    /// Every item, last first.
199    pub fn rev(&self) -> impl Iterator<Item = (&K, &V)> {
200        let mut stack = Vec::new();
201        let mut at = self.root;
202        while let Some(i) = at {
203            stack.push(i);
204            at = self.node(i).right;
205        }
206        Back { sums: self, stack }
207    }
208
209    /// The live node at index `i`.
210    fn node(&self, i: u32) -> &Node<K, V> {
211        self.nodes[i as usize].as_ref().expect("a live node")
212    }
213
214    /// The live node at index `i`, to change.
215    fn node_mut(&mut self, i: u32) -> &mut Node<K, V> {
216        self.nodes[i as usize].as_mut().expect("a live node")
217    }
218
219    /// The summary of the subtree at `at`; the empty summary when there is none.
220    fn sum(&self, at: Link) -> V::Sum {
221        at.map_or_else(V::Sum::default, |i| self.node(i).sum.clone())
222    }
223
224    /// How many items the subtree at `at` holds.
225    fn count(&self, at: Link) -> usize {
226        at.map_or(0, |i| self.node(i).count)
227    }
228
229    /// A fresh pseudo-random priority for a new node.
230    fn next_priority(&mut self) -> u64 {
231        // xorshift64*: priorities need only be unpredictable to the keys.
232        self.seed ^= self.seed >> 12;
233        self.seed ^= self.seed << 25;
234        self.seed ^= self.seed >> 27;
235        self.seed.wrapping_mul(0x2545_f491_4f6c_dd1d)
236    }
237
238    /// Stores `node` in a freed slot, or a new one; returns its index.
239    fn alloc(&mut self, node: Node<K, V>) -> u32 {
240        match self.free.pop() {
241            Some(i) => {
242                self.nodes[i as usize] = Some(node);
243                i
244            }
245            None => {
246                self.nodes.push(Some(node));
247                (self.nodes.len() - 1) as u32
248            }
249        }
250    }
251
252    /// Recomputes the summary and size of node `i` from its children's.
253    fn fix(&mut self, i: u32) {
254        let (l, r) = {
255            let n = self.node(i);
256            (n.left, n.right)
257        };
258        let sum = self
259            .sum(l)
260            .then(&self.node(i).value.summary())
261            .then(&self.sum(r));
262        let count = self.count(l) + 1 + self.count(r);
263        let n = self.node_mut(i);
264        n.sum = sum;
265        n.count = count;
266    }
267
268    /// The subtree at `at` split into the keys before `key` and the rest —
269    /// or, `through`, the keys up to and including it and the rest.
270    fn split(&mut self, at: Link, key: &K, through: bool) -> (Link, Link) {
271        let Some(i) = at else {
272            return (None, None);
273        };
274        let goes_left = if through {
275            self.node(i).key <= *key
276        } else {
277            self.node(i).key < *key
278        };
279        if goes_left {
280            let right = self.node(i).right;
281            let (l, r) = self.split(right, key, through);
282            self.node_mut(i).right = l;
283            self.fix(i);
284            (Some(i), r)
285        } else {
286            let left = self.node(i).left;
287            let (l, r) = self.split(left, key, through);
288            self.node_mut(i).left = r;
289            self.fix(i);
290            (l, Some(i))
291        }
292    }
293
294    /// Two subtrees, every key of `a` before every key of `b`, as one.
295    fn merge(&mut self, a: Link, b: Link) -> Link {
296        match (a, b) {
297            (None, b) => b,
298            (a, None) => a,
299            (Some(x), Some(y)) => {
300                if self.node(x).priority > self.node(y).priority {
301                    let right = self.node(x).right;
302                    let m = self.merge(right, Some(y));
303                    self.node_mut(x).right = m;
304                    self.fix(x);
305                    Some(x)
306                } else {
307                    let left = self.node(y).left;
308                    let m = self.merge(Some(x), left);
309                    self.node_mut(y).left = m;
310                    self.fix(y);
311                    Some(y)
312                }
313            }
314        }
315    }
316}
317
318/// An iterator over the items of a [`Sums`] in key order.
319struct Walk<'a, K, V: Item> {
320    /// The tree walked, whose arena `stack` indexes.
321    sums: &'a Sums<K, V>,
322    /// The nodes still to yield, the next on top, each before its right subtree.
323    stack: Vec<u32>,
324}
325
326impl<'a, K: Ord + Clone, V: Item> Iterator for Walk<'a, K, V> {
327    type Item = (&'a K, &'a V);
328    fn next(&mut self) -> Option<Self::Item> {
329        let i = self.stack.pop()?;
330        let n = self.sums.node(i);
331        let mut at = n.right;
332        while let Some(j) = at {
333            self.stack.push(j);
334            at = self.sums.node(j).left;
335        }
336        Some((&n.key, &n.value))
337    }
338}
339
340/// An iterator over the items of a [`Sums`], last first.
341struct Back<'a, K, V: Item> {
342    /// The tree walked, whose arena `stack` indexes.
343    sums: &'a Sums<K, V>,
344    /// The nodes still to yield, the next on top, each before its left subtree.
345    stack: Vec<u32>,
346}
347
348impl<'a, K: Ord + Clone, V: Item> Iterator for Back<'a, K, V> {
349    type Item = (&'a K, &'a V);
350    fn next(&mut self) -> Option<Self::Item> {
351        let i = self.stack.pop()?;
352        let n = self.sums.node(i);
353        let mut at = n.left;
354        while let Some(j) = at {
355            self.stack.push(j);
356            at = self.sums.node(j).right;
357        }
358        Some((&n.key, &n.value))
359    }
360}
361
362#[cfg(test)]
363mod tests;