pub trait BstSpec: Sized {
type Parent: ParentStrategy<Data = Self::Data>;
type Data;
// Required methods
fn merge(
left: Option<BstRoot<Self>>,
right: Option<BstRoot<Self>>,
) -> Option<BstRoot<Self>>;
fn split<Seeker>(
node: Option<BstRoot<Self>>,
seeker: Seeker,
equal_side: EqualSide,
) -> (Option<BstRoot<Self>>, Option<BstRoot<Self>>)
where Seeker: BstSeeker<Spec = Self>;
// Provided methods
fn top_down(_node: BstDataMutRef<'_, Self>) { ... }
fn bottom_up(_node: BstDataMutRef<'_, Self>) { ... }
}Required Associated Types§
Required Methods§
fn merge( left: Option<BstRoot<Self>>, right: Option<BstRoot<Self>>, ) -> Option<BstRoot<Self>>
fn split<Seeker>(
node: Option<BstRoot<Self>>,
seeker: Seeker,
equal_side: EqualSide,
) -> (Option<BstRoot<Self>>, Option<BstRoot<Self>>)where
Seeker: BstSeeker<Spec = Self>,
Provided Methods§
Sourcefn top_down(_node: BstDataMutRef<'_, Self>)
fn top_down(_node: BstDataMutRef<'_, Self>)
Examples found in repository?
crates/competitive/src/tree/top_tree.rs (line 410)
408 unsafe fn rake_rightmost(mut node: RakePtr<S, A>) -> RakePtr<S, A> {
409 loop {
410 unsafe { RakeBstSpec::<S, A>::top_down(BstDataMutRef::new_unchecked(node)) };
411 match unsafe { node.as_ref().child[1] } {
412 Some(right) => node = right,
413 None => return node,
414 }
415 }
416 }
417
418 unsafe fn rake_insert(
419 &mut self,
420 root: Option<RakePtr<S, A>>,
421 key: S::Point,
422 ) -> (RakePtr<S, A>, RakePtr<S, A>) {
423 let mut node = self.rake_allocator.allocate(BstNode::new(RakeData {
424 sum: key.clone(),
425 key,
426 action: <A::ActionMonoid as Unital>::unit(),
427 buffer: <A::ActionMonoid as Unital>::unit(),
428 }));
429 if let Some(mut root) = root {
430 unsafe {
431 node.as_mut().child[0] = Some(root);
432 root.as_mut().parent.parent = Some(node);
433 Self::pull_rake(node);
434 }
435 }
436 (node, node)
437 }
438
439 unsafe fn rake_remove(
440 &mut self,
441 mut node: RakePtr<S, A>,
442 ) -> (Option<RakePtr<S, A>>, A::Action) {
443 unsafe {
444 Self::splay_rake(node);
445 RakeBstSpec::<S, A>::top_down(BstDataMutRef::new_unchecked(node));
446 }
447 let left = unsafe { node.as_mut().child[0].take() };
448 let right = unsafe { node.as_mut().child[1].take() };
449 for mut child in [left, right].into_iter().flatten() {
450 unsafe { child.as_mut().parent.parent = None };
451 }
452 let root = match (left, right) {
453 (None, right) => right,
454 (left, None) => left,
455 (Some(left), Some(right)) => {
456 let mut root = unsafe { Self::rake_rightmost(left) };
457 unsafe {
458 Self::splay_rake(root);
459 root.as_mut().child[1] = Some(right);
460 (*right.as_ptr()).parent.parent = Some(root);
461 Self::pull_rake(root);
462 }
463 Some(root)
464 }
465 };
466 let node = self.rake_allocator.deallocate(node);
467 (root, node.data.buffer)
468 }
469
470 fn access_node(&mut self, node: TopPtr<S, A>) {
471 unsafe {
472 let mut previous: Option<TopPtr<S, A>> = None;
473 let mut current = Some(node);
474 while let Some(mut cursor) = current {
475 Self::splay_top(cursor);
476 let next = cursor.as_ref().parent.parent;
477 if let Some(right) = cursor.as_mut().child[1].take() {
478 let point = S::add_edge(&right.as_ref().data.sum);
479 let (light, entry) = self.rake_insert(cursor.as_ref().data.light, point);
480 cursor.as_mut().data.light = Some(light);
481 (*right.as_ptr()).data.belong = Some(entry);
482 }
483 if let Some(previous) = previous {
484 let entry = (*previous.as_ptr())
485 .data
486 .belong
487 .take()
488 .expect("a virtual path must have a rake-tree entry");
489 let (light, action) = self.rake_remove(entry);
490 cursor.as_mut().data.light = light;
491 TopBstSpec::<S, A>::apply_all(previous, &action);
492 cursor.as_mut().child[1] = Some(previous);
493 (*previous.as_ptr()).parent.parent = Some(cursor);
494 }
495 Self::pull_top(cursor);
496 previous = Some(cursor);
497 current = next;
498 }
499 Self::splay_top(node);
500 }
501 }
502
503 pub fn get(&mut self, node: usize) -> &S::Info {
504 let node = self.node(node);
505 self.access_node(node);
506 unsafe { &node.as_ref().data.info }
507 }
508
509 pub fn set(&mut self, node: usize, info: S::Info) {
510 self.modify(node, |_| info);
511 }
512
513 pub fn modify<F>(&mut self, node: usize, f: F)
514 where
515 F: FnOnce(&S::Info) -> S::Info,
516 {
517 let mut node = self.node(node);
518 self.access_node(node);
519 unsafe {
520 node.as_mut().data.info = f(&node.as_ref().data.info);
521 Self::pull_top(node);
522 }
523 }
524
525 pub fn reroot(&mut self, node: usize) {
526 let node = self.node(node);
527 self.access_node(node);
528 unsafe { TopBstSpec::<S, A>::toggle(node) };
529 }
530
531 /// `child` and `parent` must belong to different trees.
532 pub fn link(&mut self, child: usize, parent: usize) {
533 assert_ne!(child, parent);
534 self.reroot(child);
535 let child = self.node(child);
536 let mut parent = self.node(parent);
537 self.access_node(parent);
538 unsafe {
539 (*child.as_ptr()).parent.parent = Some(parent);
540 let point = S::add_edge(&child.as_ref().data.sum);
541 let (light, entry) = self.rake_insert(parent.as_ref().data.light, point);
542 parent.as_mut().data.light = Some(light);
543 (*child.as_ptr()).data.belong = Some(entry);
544 Self::pull_top(parent);
545 }
546 }
547
548 /// `(u, v)` must be an edge.
549 pub fn cut(&mut self, u: usize, v: usize) {
550 assert_ne!(u, v);
551 self.reroot(u);
552 let mut v = self.node(v);
553 self.access_node(v);
554 unsafe {
555 let mut left = v.as_mut().child[0]
556 .take()
557 .expect("the specified edge must exist");
558 left.as_mut().parent.parent = None;
559 Self::pull_top(v);
560 }
561 }
562
563 pub fn root(&mut self, node: usize) -> usize {
564 let mut root = self.node(node);
565 self.access_node(root);
566 unsafe {
567 loop {
568 TopBstSpec::<S, A>::top_down(BstDataMutRef::new_unchecked(root));
569 match root.as_ref().child[0] {
570 Some(left) => root = left,
571 None => break,
572 }
573 }
574 Self::splay_top(root);
575 root.as_ref().data.index_and_reverse >> 1
576 }
577 }
578
579 pub fn is_connected(&mut self, u: usize, v: usize) -> bool {
580 self.root(u) == self.root(v)
581 }
582
583 /// `u` and `v` must be connected.
584 pub fn fold_path(&mut self, u: usize, v: usize) -> S::Path {
585 self.reroot(u);
586 let v = self.node(v);
587 self.access_node(v);
588 unsafe { v.as_ref().data.sum.clone() }
589 }
590
591 /// `u` and `v` must be connected.
592 pub fn update_path(&mut self, u: usize, v: usize, action: &A::Action) {
593 self.reroot(u);
594 let v = self.node(v);
595 self.access_node(v);
596 if !TopBstSpec::<S, A>::is_unit(action) {
597 unsafe { TopBstSpec::<S, A>::apply_heavy(v, action) };
598 }
599 }
600
601 fn detach_left<R>(mut node: TopPtr<S, A>, f: impl FnOnce(TopPtr<S, A>) -> R) -> R {
602 unsafe {
603 let left = node.as_mut().child[0].take();
604 if let Some(mut left) = left {
605 left.as_mut().parent.parent = None;
606 }
607 Self::pull_top(node);
608 let result = f(node);
609 node.as_mut().child[0] = left;
610 if let Some(mut left) = left {
611 left.as_mut().parent.parent = Some(node);
612 }
613 Self::pull_top(node);
614 result
615 }
616 }
617
618 /// `(node, parent)` must be an edge.
619 pub fn fold_subtree(&mut self, node: usize, parent: usize) -> S::Path {
620 self.reroot(parent);
621 let node = self.node(node);
622 self.access_node(node);
623 Self::detach_left(node, |node| unsafe { node.as_ref().data.sum.clone() })
624 }
625
626 /// `(node, parent)` must be an edge.
627 pub fn update_subtree(&mut self, node: usize, parent: usize, action: &A::Action) {
628 self.reroot(parent);
629 let node = self.node(node);
630 self.access_node(node);
631 Self::detach_left(node, |node| unsafe {
632 TopBstSpec::<S, A>::apply_all(node, action);
633 TopBstSpec::<S, A>::top_down(BstDataMutRef::new_unchecked(node));
634 });
635 }More examples
crates/competitive/src/data_structure/implicit_splay_tree.rs (line 92)
83 fn update_act(mut node: BstDataMutRef<'_, Self>, act: &T::Act) {
84 if T::is_act_unit(act) {
85 return;
86 }
87 T::act_operate_assign(&mut node.data_mut().value.act, act);
88 node.data_mut().value.key = T::act_key(&node.reborrow().into_data().value.key, act);
89 if let Some(agg) = T::act_agg(&node.reborrow().into_data().value.agg, act) {
90 node.data_mut().value.agg = agg;
91 } else {
92 Self::top_down(node.reborrow_datamut());
93 Self::bottom_up(node);
94 }
95 }
96
97 fn reverse(mut node: BstDataMutRef<'_, Self>) {
98 node.swap_children();
99 let data = node.data_mut();
100 T::toggle(&mut data.value.agg);
101 data.rev ^= true;
102 }
103}
104
105impl<T> BstSpec for ImplicitSplayTreeSpec<T>
106where
107 T: LazyMapMonoid,
108{
109 type Parent = WithNoParent<Self::Data>;
110 type Data = ImplicitSplayTreeData<T>;
111
112 fn top_down(mut node: BstDataMutRef<'_, Self>) {
113 if !T::is_act_unit(&node.reborrow().into_data().value.act) {
114 let act = replace(&mut node.data_mut().value.act, T::act_unit());
115 if let Ok(left) = node.reborrow_datamut().left().descend() {
116 Self::update_act(left, &act);
117 }
118 if let Ok(right) = node.reborrow_datamut().right().descend() {
119 Self::update_act(right, &act);
120 }
121 }
122 if node.reborrow().into_data().rev {
123 node.data_mut().rev = false;
124 if let Ok(left) = node.reborrow_datamut().left().descend() {
125 Self::reverse(left);
126 }
127 if let Ok(right) = node.reborrow_datamut().right().descend() {
128 Self::reverse(right);
129 }
130 }
131 }
132
133 fn bottom_up(mut node: BstDataMutRef<'_, Self>) {
134 let mut agg = T::single_agg(&node.reborrow().into_data().value.key);
135 let mut size = 1;
136 if let Ok(left) = node.reborrow().left().descend() {
137 let data = left.into_data();
138 agg = T::agg_operate(&data.value.agg, &agg);
139 size += data.size;
140 }
141 if let Ok(right) = node.reborrow().right().descend() {
142 let data = right.into_data();
143 agg = T::agg_operate(&agg, &data.value.agg);
144 size += data.size;
145 }
146 let data = node.data_mut();
147 data.value.agg = agg;
148 data.size = size;
149 }
150
151 fn merge(
152 left: Option<ImplicitSplayTreeRoot<T>>,
153 right: Option<ImplicitSplayTreeRoot<T>>,
154 ) -> Option<ImplicitSplayTreeRoot<T>> {
155 splay_operations::merge(left, right)
156 }
157
158 fn split<Seeker>(
159 node: Option<ImplicitSplayTreeRoot<T>>,
160 seeker: Seeker,
161 equal_side: EqualSide,
162 ) -> (
163 Option<ImplicitSplayTreeRoot<T>>,
164 Option<ImplicitSplayTreeRoot<T>>,
165 )
166 where
167 Seeker: BstSeeker<Spec = Self>,
168 {
169 splay_operations::split(node, seeker, equal_side)
170 }
171}
172
173pub struct ImplicitSplayTree<T, A = MemoryPool<ImplicitSplayTreeNode<T>>>
174where
175 T: LazyMapMonoid,
176 A: Allocator<ImplicitSplayTreeNode<T>>,
177{
178 root: Option<ImplicitSplayTreeRoot<T>>,
179 length: usize,
180 allocator: ManuallyDrop<A>,
181 _marker: PhantomData<fn() -> T>,
182}
183
184impl<T, A> Default for ImplicitSplayTree<T, A>
185where
186 T: LazyMapMonoid,
187 A: Allocator<ImplicitSplayTreeNode<T>> + Default,
188{
189 fn default() -> Self {
190 Self {
191 root: None,
192 length: 0,
193 allocator: ManuallyDrop::new(A::default()),
194 _marker: PhantomData,
195 }
196 }
197}
198
199impl<T, A> Drop for ImplicitSplayTree<T, A>
200where
201 T: LazyMapMonoid,
202 A: Allocator<ImplicitSplayTreeNode<T>>,
203{
204 fn drop(&mut self) {
205 unsafe {
206 if let Some(root) = self.root.take() {
207 root.into_dying().drop_all(self.allocator.deref_mut());
208 }
209 ManuallyDrop::drop(&mut self.allocator);
210 }
211 }
212}
213
214impl<T> ImplicitSplayTree<T>
215where
216 T: LazyMapMonoid,
217{
218 pub fn new() -> Self {
219 Self::default()
220 }
221
222 pub fn with_capacity(capacity: usize) -> Self {
223 Self {
224 root: None,
225 length: 0,
226 allocator: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
227 _marker: PhantomData,
228 }
229 }
230}
231
232impl<T, A> ImplicitSplayTree<T, A>
233where
234 T: LazyMapMonoid,
235 A: Allocator<ImplicitSplayTreeNode<T>>,
236{
237 fn node(&mut self, key: T::Key) -> ImplicitSplayTreeRoot<T> {
238 BstRoot::from_data(
239 ImplicitSplayTreeData {
240 value: LazyMapElement::from_key(key),
241 size: 1,
242 rev: false,
243 },
244 self.allocator.deref_mut(),
245 )
246 }
247
248 #[inline]
249 fn splay<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
250 where
251 Seeker: BstSeeker<Spec = ImplicitSplayTreeSpec<T>>,
252 {
253 let (ordering, root) = splay_operations::splay(self.root.take()?, seeker);
254 self.root = Some(root);
255 Some(ordering)
256 }
257
258 pub fn len(&self) -> usize {
259 self.length
260 }
261
262 pub fn is_empty(&self) -> bool {
263 self.length == 0
264 }
265
266 pub fn update<R>(&mut self, range: R, act: T::Act)
267 where
268 R: RangeBounds<usize>,
269 {
270 let mut split = Split3::seek_by_size(&mut self.root, range);
271 if let Some(root) = split.mid_datamut() {
272 ImplicitSplayTreeSpec::update_act(root, &act);
273 }
274 }
275
276 pub fn fold<R>(&mut self, range: R) -> T::Agg
277 where
278 R: RangeBounds<usize>,
279 {
280 let split = Split3::seek_by_size(&mut self.root, range);
281 split
282 .mid()
283 .map(|node| node.into_data().value.agg.clone())
284 .unwrap_or_else(T::agg_unit)
285 }
286
287 pub fn reverse<R>(&mut self, range: R)
288 where
289 R: RangeBounds<usize>,
290 {
291 let mut split = Split3::seek_by_size(&mut self.root, range);
292 if let Some(root) = split.mid_datamut() {
293 ImplicitSplayTreeSpec::reverse(root);
294 }
295 }
296
297 pub fn get(&mut self, index: usize) -> Option<&T::Key> {
298 if index >= self.length {
299 return None;
300 }
301 self.splay(SeekBySize::new(index));
302 Some(&self.root.as_ref()?.reborrow().into_data().value.key)
303 }
304
305 pub fn modify<F>(&mut self, index: usize, f: F)
306 where
307 F: FnOnce(&T::Key) -> T::Key,
308 {
309 assert!(index < self.length);
310 self.splay(SeekBySize::new(index));
311 let mut root = self.root.as_mut().unwrap().borrow_datamut();
312 ImplicitSplayTreeSpec::top_down(root.reborrow_datamut());
313 {
314 let data = root.data_mut();
315 data.value.key = f(&data.value.key);
316 }
317 ImplicitSplayTreeSpec::bottom_up(root);
318 }
319
320 pub fn insert(&mut self, index: usize, key: T::Key) {
321 assert!(index <= self.length);
322 let mut node = self.node(key);
323 if self.root.is_none() {
324 self.root = Some(node);
325 } else if index == self.length {
326 self.splay(SeekBySize::new(index));
327 unsafe { node.borrow_mut().left_mut().set(self.root.take().unwrap()) };
328 ImplicitSplayTreeSpec::bottom_up(node.borrow_datamut());
329 self.root = Some(node);
330 } else {
331 self.splay(SeekBySize::new(index));
332 let mut root = self.root.take().unwrap();
333 let left = unsafe { root.borrow_mut().left_mut().take() };
334 if let Some(left) = left {
335 unsafe { node.borrow_mut().left_mut().set(left) };
336 }
337 ImplicitSplayTreeSpec::bottom_up(root.borrow_datamut());
338 unsafe { node.borrow_mut().right_mut().set(root) };
339 ImplicitSplayTreeSpec::bottom_up(node.borrow_datamut());
340 self.root = Some(node);
341 }
342 self.length += 1;
343 }
344
345 pub fn remove(&mut self, index: usize) -> Option<T::Key> {
346 if index >= self.length {
347 return None;
348 }
349 self.splay(SeekBySize::new(index));
350 let mut node = self.root.take().unwrap();
351 ImplicitSplayTreeSpec::top_down(node.borrow_datamut());
352 let left = unsafe { node.borrow_mut().left_mut().take() };
353 let right = unsafe { node.borrow_mut().right_mut().take() };
354 self.root = ImplicitSplayTreeSpec::merge(left, right);
355 self.length -= 1;
356 let data = unsafe { node.into_dying().into_data(self.allocator.deref_mut()) };
357 Some(data.value.key)
358 }crates/competitive/src/data_structure/implicit_treap.rs (line 93)
84 fn update_act(mut node: BstDataMutRef<'_, Self>, act: &T::Act) {
85 if T::is_act_unit(act) {
86 return;
87 }
88 T::act_operate_assign(&mut node.data_mut().value.act, act);
89 node.data_mut().value.key = T::act_key(&node.reborrow().into_data().value.key, act);
90 if let Some(agg) = T::act_agg(&node.reborrow().into_data().value.agg, act) {
91 node.data_mut().value.agg = agg;
92 } else {
93 Self::top_down(node.reborrow_datamut());
94 Self::bottom_up(node);
95 }
96 }
97
98 fn reverse(mut node: BstDataMutRef<'_, Self>) {
99 node.swap_children();
100 let data = node.data_mut();
101 T::toggle(&mut data.value.agg);
102 data.rev ^= true;
103 }
104}
105
106impl<T> BstSpec for ImplicitTreapSpec<T>
107where
108 T: LazyMapMonoid,
109{
110 type Parent = WithNoParent<Self::Data>;
111 type Data = ImplicitTreapData<T>;
112
113 fn top_down(mut node: BstDataMutRef<'_, Self>) {
114 if !T::is_act_unit(&node.reborrow().into_data().value.act) {
115 let act = replace(&mut node.data_mut().value.act, T::act_unit());
116 if let Ok(left) = node.reborrow_datamut().left().descend() {
117 Self::update_act(left, &act);
118 }
119 if let Ok(right) = node.reborrow_datamut().right().descend() {
120 Self::update_act(right, &act);
121 }
122 }
123 if node.reborrow().into_data().rev {
124 node.data_mut().rev = false;
125 if let Ok(left) = node.reborrow_datamut().left().descend() {
126 Self::reverse(left);
127 }
128 if let Ok(right) = node.reborrow_datamut().right().descend() {
129 Self::reverse(right);
130 }
131 }
132 }
133
134 fn bottom_up(mut node: BstDataMutRef<'_, Self>) {
135 let mut agg = T::single_agg(&node.reborrow().into_data().value.key);
136 let mut size = 1;
137 if let Ok(left) = node.reborrow().left().descend() {
138 let data = left.into_data();
139 agg = T::agg_operate(&data.value.agg, &agg);
140 size += data.size;
141 }
142 if let Ok(right) = node.reborrow().right().descend() {
143 let data = right.into_data();
144 agg = T::agg_operate(&agg, &data.value.agg);
145 size += data.size;
146 }
147 let data = node.data_mut();
148 data.value.agg = agg;
149 data.size = size;
150 }
151
152 fn merge(
153 left: Option<ImplicitTreapRoot<T>>,
154 right: Option<ImplicitTreapRoot<T>>,
155 ) -> Option<ImplicitTreapRoot<T>> {
156 match (left, right) {
157 (None, None) => None,
158 (None, Some(node)) | (Some(node), None) => Some(node),
159 (Some(mut left), Some(mut right)) => unsafe {
160 if left.reborrow().into_data().priority > right.reborrow().into_data().priority {
161 Self::top_down(left.borrow_datamut());
162 let lr = left.borrow_mut().right().take();
163 let lr = Self::merge(lr, Some(right)).unwrap_unchecked();
164 left.borrow_mut().right().set(lr);
165 Self::bottom_up(left.borrow_datamut());
166 Some(left)
167 } else {
168 Self::top_down(right.borrow_datamut());
169 let rl = right.borrow_mut().left().take();
170 let rl = Self::merge(Some(left), rl).unwrap_unchecked();
171 right.borrow_mut().left().set(rl);
172 Self::bottom_up(right.borrow_datamut());
173 Some(right)
174 }
175 },
176 }
177 }
178
179 fn split<Seeker>(
180 node: Option<ImplicitTreapRoot<T>>,
181 mut seeker: Seeker,
182 equal_side: EqualSide,
183 ) -> (Option<ImplicitTreapRoot<T>>, Option<ImplicitTreapRoot<T>>)
184 where
185 Seeker: BstSeeker<Spec = Self>,
186 {
187 match node {
188 None => (None, None),
189 Some(mut node) => {
190 Self::top_down(node.borrow_datamut());
191 if equal_side.goes_left(seeker.bst_seek(node.reborrow())) {
192 unsafe {
193 let right = node.borrow_mut().right().take();
194 let (l, r) = Self::split(right, seeker, equal_side);
195 if let Some(l) = l {
196 node.borrow_mut().right().set(l);
197 }
198 Self::bottom_up(node.borrow_datamut());
199 (Some(node), r)
200 }
201 } else {
202 unsafe {
203 let left = node.borrow_mut().left().take();
204 let (l, r) = Self::split(left, seeker, equal_side);
205 if let Some(r) = r {
206 node.borrow_mut().left().set(r);
207 }
208 Self::bottom_up(node.borrow_datamut());
209 (l, Some(node))
210 }
211 }
212 }
213 }
214 }
215}
216
217pub struct ImplicitTreap<T, A = MemoryPool<ImplicitTreapNode<T>>>
218where
219 T: LazyMapMonoid,
220 A: Allocator<ImplicitTreapNode<T>>,
221{
222 root: Option<ImplicitTreapRoot<T>>,
223 length: usize,
224 rng: Xorshift,
225 allocator: ManuallyDrop<A>,
226 _marker: PhantomData<fn() -> T>,
227}
228
229impl<T, A> Default for ImplicitTreap<T, A>
230where
231 T: LazyMapMonoid,
232 A: Allocator<ImplicitTreapNode<T>> + Default,
233{
234 fn default() -> Self {
235 Self {
236 root: None,
237 length: 0,
238 rng: Xorshift::new(),
239 allocator: ManuallyDrop::new(A::default()),
240 _marker: PhantomData,
241 }
242 }
243}
244
245impl<T, A> Drop for ImplicitTreap<T, A>
246where
247 T: LazyMapMonoid,
248 A: Allocator<ImplicitTreapNode<T>>,
249{
250 fn drop(&mut self) {
251 unsafe {
252 if let Some(root) = self.root.take() {
253 root.into_dying().drop_all(self.allocator.deref_mut());
254 }
255 ManuallyDrop::drop(&mut self.allocator);
256 }
257 }
258}
259
260impl<T> ImplicitTreap<T>
261where
262 T: LazyMapMonoid,
263{
264 pub fn new() -> Self {
265 Self::default()
266 }
267
268 pub fn with_capacity(capacity: usize) -> Self {
269 Self {
270 root: None,
271 length: 0,
272 rng: Xorshift::new(),
273 allocator: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
274 _marker: PhantomData,
275 }
276 }
277}
278
279impl<T, A> ImplicitTreap<T, A>
280where
281 T: LazyMapMonoid,
282 A: Allocator<ImplicitTreapNode<T>>,
283{
284 fn node(&mut self, key: T::Key) -> ImplicitTreapRoot<T> {
285 BstRoot::from_data(
286 ImplicitTreapData {
287 priority: self.rng.rand64(),
288 value: LazyMapElement::from_key(key),
289 size: 1,
290 rev: false,
291 },
292 self.allocator.deref_mut(),
293 )
294 }
295
296 fn build<I>(&mut self, iter: I) -> (Option<ImplicitTreapRoot<T>>, usize)
297 where
298 I: IntoIterator<Item = T::Key>,
299 {
300 let mut stack = vec![];
301 let mut len = 0;
302 for key in iter {
303 let mut cur = self.node(key).node;
304 let mut left = None;
305 unsafe {
306 while stack
307 .last()
308 .is_some_and(|node: &NonNull<ImplicitTreapNode<T>>| {
309 node.as_ref().data.priority < cur.as_ref().data.priority
310 })
311 {
312 left = stack.pop();
313 }
314 cur.as_mut().child[0] = left;
315 if let Some(parent) = stack.last_mut() {
316 parent.as_mut().child[1] = Some(cur);
317 }
318 }
319 stack.push(cur);
320 len += 1;
321 }
322 let root = stack.first().copied().map(BstRoot::new);
323 if let Some(mut root) = root {
324 Self::build_bottom_up(root.borrow_datamut());
325 (Some(root), len)
326 } else {
327 (None, len)
328 }
329 }
330
331 fn build_bottom_up(mut node: BstDataMutRef<'_, ImplicitTreapSpec<T>>) {
332 if let Ok(left) = node.reborrow_datamut().left().descend() {
333 Self::build_bottom_up(left);
334 }
335 if let Ok(right) = node.reborrow_datamut().right().descend() {
336 Self::build_bottom_up(right);
337 }
338 ImplicitTreapSpec::<T>::bottom_up(node);
339 }
340
341 pub fn len(&self) -> usize {
342 self.length
343 }
344
345 pub fn is_empty(&self) -> bool {
346 self.length == 0
347 }
348
349 pub fn update<R>(&mut self, range: R, x: T::Act)
350 where
351 R: RangeBounds<usize>,
352 {
353 let mut split = Split3::seek_by_size(&mut self.root, range);
354 if let Some(root) = split.mid_datamut() {
355 ImplicitTreapSpec::<T>::update_act(root, &x);
356 }
357 }
358
359 pub fn fold<R>(&mut self, range: R) -> T::Agg
360 where
361 R: RangeBounds<usize>,
362 {
363 let split = Split3::seek_by_size(&mut self.root, range);
364 split
365 .mid()
366 .map(|node| node.into_data().value.agg.clone())
367 .unwrap_or_else(T::agg_unit)
368 }
369
370 pub fn reverse<R>(&mut self, range: R)
371 where
372 R: RangeBounds<usize>,
373 {
374 let mut split = Split3::seek_by_size(&mut self.root, range);
375 if let Some(root) = split.mid_datamut() {
376 ImplicitTreapSpec::<T>::reverse(root);
377 }
378 }
379
380 pub fn get(&mut self, index: usize) -> Option<&T::Key> {
381 if index >= self.length {
382 return None;
383 }
384 let split = Split3::seek_by_size(&mut self.root, index..=index);
385 let node = split.mid()?.node;
386 drop(split);
387 Some(unsafe { &(*node.as_ptr()).data.value.key })
388 }
389
390 pub fn modify<F>(&mut self, index: usize, f: F)
391 where
392 F: FnOnce(&T::Key) -> T::Key,
393 {
394 assert!(index < self.length);
395 let mut split = Split3::seek_by_size(&mut self.root, index..=index);
396 let mut node = split.mid_datamut().unwrap();
397 ImplicitTreapSpec::<T>::top_down(node.reborrow_datamut());
398 {
399 let data = node.data_mut();
400 data.value.key = f(&data.value.key);
401 }
402 ImplicitTreapSpec::<T>::bottom_up(node);
403 }
404
405 pub fn insert(&mut self, index: usize, x: T::Key) {
406 assert!(index <= self.length);
407 let node = self.node(x);
408 if index == 0 {
409 self.root = ImplicitTreapSpec::<T>::merge(Some(node), self.root.take());
410 } else if index == self.length {
411 self.root = ImplicitTreapSpec::<T>::merge(self.root.take(), Some(node));
412 } else {
413 let mut node = Some(node);
414 let mut split = Split::new(&mut self.root, SeekBySize::new(index), EqualSide::Right);
415 split.manually_merge(|left, right| {
416 ImplicitTreapSpec::<T>::merge(
417 ImplicitTreapSpec::<T>::merge(left, node.take()),
418 right,
419 )
420 });
421 }
422 self.length += 1;
423 }
424
425 pub fn remove(&mut self, index: usize) -> Option<T::Key> {
426 if index >= self.length {
427 return None;
428 }
429 let mid;
430 if index == 0 {
431 let (left, right) = ImplicitTreapSpec::<T>::split(
432 self.root.take(),
433 SeekBySize::new(1),
434 EqualSide::Right,
435 );
436 mid = left;
437 self.root = right;
438 } else if index + 1 == self.length {
439 let (left, right) = ImplicitTreapSpec::<T>::split(
440 self.root.take(),
441 SeekBySize::new(index),
442 EqualSide::Right,
443 );
444 mid = right;
445 self.root = left;
446 } else {
447 let (left, rest) = ImplicitTreapSpec::<T>::split(
448 self.root.take(),
449 SeekBySize::new(index),
450 EqualSide::Right,
451 );
452 let (middle, right) =
453 ImplicitTreapSpec::<T>::split(rest, SeekBySize::new(1), EqualSide::Right);
454 mid = middle;
455 self.root = ImplicitTreapSpec::<T>::merge(left, right);
456 }
457 self.length -= 1;
458 let mut node = mid.unwrap();
459 ImplicitTreapSpec::<T>::top_down(node.borrow_datamut());
460 let data = unsafe { node.into_dying().into_data(self.allocator.deref_mut()) };
461 Some(data.value.key)
462 }crates/competitive/src/data_structure/binary_search_tree/node.rs (line 146)
139 pub fn resolve_top_down<Spec>(node: BstNodeRef<marker::DataMut<'_>, Spec>)
140 where
141 Spec: BstSpec<Data = Data, Parent = Self>,
142 {
143 unsafe {
144 let (mut node, mut stack) = node.root_path();
145 while let Some(is_left) = stack.pop() {
146 Spec::top_down(node.reborrow_datamut());
147 if is_left {
148 node = node.left().descend().unwrap_unchecked();
149 } else {
150 node = node.right().descend().unwrap_unchecked();
151 }
152 }
153 Spec::top_down(node.reborrow_datamut());
154 }
155 }crates/competitive/src/tree/link_cut_tree.rs (line 248)
233 fn access_node(mut node: LinkCutPtr<S>) {
234 unsafe {
235 Self::splay(node);
236 if let Some(right) = node.as_mut().child[1].take() {
237 LinkCutBstSpec::<S>::with_two_inner_mut(node, right, S::attach_virtual);
238 }
239 Self::pull(node);
240 while let Some(mut parent) = node.as_ref().parent.parent {
241 Self::splay(parent);
242 if let Some(right) = parent.as_mut().child[1].take() {
243 LinkCutBstSpec::<S>::with_two_inner_mut(parent, right, S::attach_virtual);
244 }
245 LinkCutBstSpec::<S>::with_two_inner_mut(parent, node, S::detach_virtual);
246 parent.as_mut().child[1] = Some(node);
247 node.as_mut().parent.parent = Some(parent);
248 LinkCutBstSpec::<S>::top_down(BstDataMutRef::new_unchecked(node));
249 splay_operations::with_parent::rotate::<LinkCutBstSpec<S>, LinkCutData<S>>(node);
250 Self::pull(node);
251 LinkCutBstSpec::<S>::with_two_inner_mut(parent, node, S::transfer_path_parent);
252 }
253 }
254 }
255
256 pub fn get(&mut self, node: usize) -> &S::Value {
257 let node = self.node(node);
258 Self::access_node(node);
259 unsafe { S::value(&node.as_ref().data.inner) }
260 }
261
262 pub fn set(&mut self, node: usize, value: S::Value) {
263 self.modify(node, |_| value);
264 }
265
266 pub fn modify<F>(&mut self, node: usize, f: F)
267 where
268 F: FnOnce(&S::Value) -> S::Value,
269 {
270 let node = self.node(node);
271 if S::MODIFY_REQUIRES_ACCESS {
272 Self::access_node(node);
273 } else {
274 unsafe { Self::splay(node) };
275 }
276 unsafe {
277 let data = &mut (*node.as_ptr()).data.inner;
278 *S::value_mut(data) = f(S::value(data));
279 Self::pull(node);
280 }
281 }
282
283 pub fn reroot(&mut self, node: usize) {
284 let node = self.node(node);
285 Self::access_node(node);
286 unsafe { LinkCutBstSpec::<S>::toggle(node) };
287 }
288
289 /// `child` and `parent` must belong to different trees.
290 pub fn link(&mut self, child: usize, parent: usize) {
291 assert_ne!(child, parent);
292 self.reroot(child);
293 let child = self.node(child);
294 let parent = self.node(parent);
295 Self::access_node(parent);
296 unsafe {
297 (*child.as_ptr()).parent.parent = Some(parent);
298 LinkCutBstSpec::<S>::with_two_inner_mut(parent, child, S::attach_virtual);
299 Self::pull(parent);
300 }
301 }
302
303 /// `(u, v)` must be an edge.
304 pub fn cut(&mut self, u: usize, v: usize) {
305 assert_ne!(u, v);
306 self.reroot(u);
307 let mut v = self.node(v);
308 Self::access_node(v);
309 unsafe {
310 let mut left = v.as_mut().child[0]
311 .take()
312 .expect("the specified edge must exist");
313 left.as_mut().parent.parent = None;
314 Self::pull(v);
315 }
316 }
317
318 pub fn root(&mut self, node: usize) -> usize {
319 let mut root = self.node(node);
320 Self::access_node(root);
321 unsafe {
322 loop {
323 LinkCutBstSpec::<S>::top_down(BstDataMutRef::new_unchecked(root));
324 match root.as_ref().child[0] {
325 Some(left) => root = left,
326 None => break,
327 }
328 }
329 Self::splay(root);
330 root.as_ref().data.index_and_reverse >> 1
331 }
332 }
333
334 pub fn is_connected(&mut self, u: usize, v: usize) -> bool {
335 self.root(u) == self.root(v)
336 }
337
338 fn detach_left<R>(node: LinkCutPtr<S>, f: impl FnOnce(&mut S::Data) -> R) -> R {
339 unsafe {
340 let left = (*node.as_ptr()).child[0].take();
341 if let Some(mut left) = left {
342 left.as_mut().parent.parent = None;
343 }
344 Self::pull(node);
345 let result = f(&mut (*node.as_ptr()).data.inner);
346 LinkCutBstSpec::<S>::top_down(BstDataMutRef::new_unchecked(node));
347 (*node.as_ptr()).child[0] = left;
348 if let Some(mut left) = left {
349 left.as_mut().parent.parent = Some(node);
350 }
351 Self::pull(node);
352 result
353 }
354 }crates/competitive/src/data_structure/treap.rs (line 126)
117 fn merge(
118 left: Option<TreapRoot<M, L>>,
119 right: Option<TreapRoot<M, L>>,
120 ) -> Option<TreapRoot<M, L>> {
121 match (left, right) {
122 (None, None) => None,
123 (None, Some(node)) | (Some(node), None) => Some(node),
124 (Some(mut left), Some(mut right)) => unsafe {
125 if left.reborrow().into_data().priority > right.reborrow().into_data().priority {
126 TreapSpec::top_down(left.borrow_datamut());
127 let lr = left.borrow_mut().right().take();
128 let lr = Self::merge(lr, Some(right)).unwrap_unchecked();
129 left.borrow_mut().right().set(lr);
130 TreapSpec::bottom_up(left.borrow_datamut());
131 Some(left)
132 } else {
133 TreapSpec::top_down(right.borrow_datamut());
134 let rl = right.borrow_mut().left().take();
135 let rl = Self::merge(Some(left), rl).unwrap_unchecked();
136 right.borrow_mut().left().set(rl);
137 TreapSpec::bottom_up(right.borrow_datamut());
138 Some(right)
139 }
140 },
141 }
142 }
143
144 fn split<Seeker>(
145 node: Option<TreapRoot<M, L>>,
146 mut seeker: Seeker,
147 equal_side: EqualSide,
148 ) -> (Option<TreapRoot<M, L>>, Option<TreapRoot<M, L>>)
149 where
150 Seeker: BstSeeker<Spec = Self>,
151 {
152 match node {
153 None => (None, None),
154 Some(mut node) => {
155 Self::top_down(node.borrow_datamut());
156 if equal_side.goes_left(seeker.bst_seek(node.reborrow())) {
157 unsafe {
158 let right = node.borrow_mut().right().take();
159 let (l, r) = Self::split(right, seeker, equal_side);
160 if let Some(l) = l {
161 node.borrow_mut().right().set(l);
162 }
163 Self::bottom_up(node.borrow_datamut());
164 (Some(node), r)
165 }
166 } else {
167 unsafe {
168 let left = node.borrow_mut().left().take();
169 let (l, r) = Self::split(left, seeker, equal_side);
170 if let Some(r) = r {
171 node.borrow_mut().left().set(r);
172 }
173 Self::bottom_up(node.borrow_datamut());
174 (l, Some(node))
175 }
176 }
177 }
178 }
179 }
180}
181
182impl<M, L> TreapSpec<M, L>
183where
184 M: MonoidAct<Key: Ord>,
185 L: LazyMapMonoid,
186{
187 pub fn merge_ordered(
188 left: Option<TreapRoot<M, L>>,
189 right: Option<TreapRoot<M, L>>,
190 ) -> Option<TreapRoot<M, L>> {
191 match (left, right) {
192 (None, None) => None,
193 (None, Some(node)) | (Some(node), None) => Some(node),
194 (Some(mut left), Some(mut right)) => unsafe {
195 if left.reborrow().into_data().priority > right.reborrow().into_data().priority {
196 Self::top_down(left.borrow_datamut());
197 let key = &left.reborrow().into_data().key.key;
198 let (rl, rr) = Self::split(Some(right), SeekByKey::new(key), EqualSide::Right);
199 let ll = left.borrow_mut().left().take();
200 let lr = left.borrow_mut().right().take();
201 if let Some(l) = Self::merge_ordered(ll, rl) {
202 left.borrow_mut().left().set(l);
203 }
204 if let Some(r) = Self::merge_ordered(lr, rr) {
205 left.borrow_mut().right().set(r);
206 }
207 Self::bottom_up(left.borrow_datamut());
208 Some(left)
209 } else {
210 Self::top_down(right.borrow_datamut());
211 let key = &right.reborrow().into_data().key.key;
212 let (ll, lr) = Self::split(Some(left), SeekByKey::new(key), EqualSide::Right);
213 let rl = right.borrow_mut().left().take();
214 let rr = right.borrow_mut().right().take();
215 if let Some(l) = Self::merge_ordered(ll, rl) {
216 right.borrow_mut().left().set(l);
217 }
218 if let Some(r) = Self::merge_ordered(lr, rr) {
219 right.borrow_mut().right().set(r);
220 }
221 Self::bottom_up(right.borrow_datamut());
222 Some(right)
223 }
224 },
225 }
226 }Additional examples can be found in:
Sourcefn bottom_up(_node: BstDataMutRef<'_, Self>)
fn bottom_up(_node: BstDataMutRef<'_, Self>)
Examples found in repository?
More examples
crates/competitive/src/data_structure/binary_search_tree/node.rs (line 162)
157 pub fn resolve_bottom_up<Spec>(mut node: BstNodeRef<marker::DataMut<'_>, Spec>)
158 where
159 Spec: BstSpec<Data = Data, Parent = Self>,
160 {
161 loop {
162 Spec::bottom_up(node.reborrow_datamut());
163 match node.ascend() {
164 Ok(parent) => node = parent,
165 Err(_) => break,
166 }
167 }
168 }
169
170 pub fn is_root<Spec>(node: BstNodeRef<marker::Immut<'_>, Spec>) -> bool
171 where
172 Spec: BstSpec<Data = Data, Parent = Self>,
173 {
174 unsafe { node.node.as_ref().parent.parent.is_none() }
175 }
176
177 pub unsafe fn remove_root<Spec>(
178 root: &mut Option<BstRoot<Spec>>,
179 ) -> Option<BstNodeRef<marker::Owned, Spec>>
180 where
181 Spec: BstSpec<Data = Data, Parent = Self>,
182 {
183 let mut node = root.take()?;
184 unsafe {
185 let left = node.borrow_mut().left_mut().take();
186 let right = node.borrow_mut().right_mut().take();
187 *root = Spec::merge(left, right);
188 Spec::bottom_up(node.borrow_datamut());
189 Some(node)
190 }
191 }
192
193 pub unsafe fn remove_not_root<Spec>(
194 mut node: BstNodeRef<marker::Mut<'_>, Spec>,
195 ) -> BstNodeRef<marker::Owned, Spec>
196 where
197 Spec: BstSpec<Data = Data, Parent = Self>,
198 {
199 assert!(!Self::is_root(node.reborrow()));
200 unsafe {
201 let left = node.left_mut().take();
202 let right = node.right_mut().take();
203 let merged = Spec::merge(left, right);
204 let node_inner = node.node;
205 let mut parent = node.ascend().unwrap_unchecked();
206 let mut node = if let Some(merged) = merged {
207 let node = if parent
208 .reborrow()
209 .left()
210 .descend()
211 .is_ok_and(|n| n.node == node_inner)
212 {
213 parent.left_mut().replace(merged)
214 } else {
215 parent.right_mut().replace(merged)
216 };
217 Self::resolve_bottom_up(parent.reborrow_datamut());
218 node.unwrap_unchecked()
219 } else {
220 let node = if parent
221 .reborrow()
222 .left()
223 .descend()
224 .is_ok_and(|n| n.node == node_inner)
225 {
226 parent.left_mut().take()
227 } else {
228 parent.right_mut().take()
229 };
230 Self::resolve_bottom_up(parent.reborrow_datamut());
231 node.unwrap_unchecked()
232 };
233 Spec::bottom_up(node.borrow_datamut());
234 node
235 }
236 }crates/competitive/src/data_structure/implicit_splay_tree.rs (line 93)
83 fn update_act(mut node: BstDataMutRef<'_, Self>, act: &T::Act) {
84 if T::is_act_unit(act) {
85 return;
86 }
87 T::act_operate_assign(&mut node.data_mut().value.act, act);
88 node.data_mut().value.key = T::act_key(&node.reborrow().into_data().value.key, act);
89 if let Some(agg) = T::act_agg(&node.reborrow().into_data().value.agg, act) {
90 node.data_mut().value.agg = agg;
91 } else {
92 Self::top_down(node.reborrow_datamut());
93 Self::bottom_up(node);
94 }
95 }
96
97 fn reverse(mut node: BstDataMutRef<'_, Self>) {
98 node.swap_children();
99 let data = node.data_mut();
100 T::toggle(&mut data.value.agg);
101 data.rev ^= true;
102 }
103}
104
105impl<T> BstSpec for ImplicitSplayTreeSpec<T>
106where
107 T: LazyMapMonoid,
108{
109 type Parent = WithNoParent<Self::Data>;
110 type Data = ImplicitSplayTreeData<T>;
111
112 fn top_down(mut node: BstDataMutRef<'_, Self>) {
113 if !T::is_act_unit(&node.reborrow().into_data().value.act) {
114 let act = replace(&mut node.data_mut().value.act, T::act_unit());
115 if let Ok(left) = node.reborrow_datamut().left().descend() {
116 Self::update_act(left, &act);
117 }
118 if let Ok(right) = node.reborrow_datamut().right().descend() {
119 Self::update_act(right, &act);
120 }
121 }
122 if node.reborrow().into_data().rev {
123 node.data_mut().rev = false;
124 if let Ok(left) = node.reborrow_datamut().left().descend() {
125 Self::reverse(left);
126 }
127 if let Ok(right) = node.reborrow_datamut().right().descend() {
128 Self::reverse(right);
129 }
130 }
131 }
132
133 fn bottom_up(mut node: BstDataMutRef<'_, Self>) {
134 let mut agg = T::single_agg(&node.reborrow().into_data().value.key);
135 let mut size = 1;
136 if let Ok(left) = node.reborrow().left().descend() {
137 let data = left.into_data();
138 agg = T::agg_operate(&data.value.agg, &agg);
139 size += data.size;
140 }
141 if let Ok(right) = node.reborrow().right().descend() {
142 let data = right.into_data();
143 agg = T::agg_operate(&agg, &data.value.agg);
144 size += data.size;
145 }
146 let data = node.data_mut();
147 data.value.agg = agg;
148 data.size = size;
149 }
150
151 fn merge(
152 left: Option<ImplicitSplayTreeRoot<T>>,
153 right: Option<ImplicitSplayTreeRoot<T>>,
154 ) -> Option<ImplicitSplayTreeRoot<T>> {
155 splay_operations::merge(left, right)
156 }
157
158 fn split<Seeker>(
159 node: Option<ImplicitSplayTreeRoot<T>>,
160 seeker: Seeker,
161 equal_side: EqualSide,
162 ) -> (
163 Option<ImplicitSplayTreeRoot<T>>,
164 Option<ImplicitSplayTreeRoot<T>>,
165 )
166 where
167 Seeker: BstSeeker<Spec = Self>,
168 {
169 splay_operations::split(node, seeker, equal_side)
170 }
171}
172
173pub struct ImplicitSplayTree<T, A = MemoryPool<ImplicitSplayTreeNode<T>>>
174where
175 T: LazyMapMonoid,
176 A: Allocator<ImplicitSplayTreeNode<T>>,
177{
178 root: Option<ImplicitSplayTreeRoot<T>>,
179 length: usize,
180 allocator: ManuallyDrop<A>,
181 _marker: PhantomData<fn() -> T>,
182}
183
184impl<T, A> Default for ImplicitSplayTree<T, A>
185where
186 T: LazyMapMonoid,
187 A: Allocator<ImplicitSplayTreeNode<T>> + Default,
188{
189 fn default() -> Self {
190 Self {
191 root: None,
192 length: 0,
193 allocator: ManuallyDrop::new(A::default()),
194 _marker: PhantomData,
195 }
196 }
197}
198
199impl<T, A> Drop for ImplicitSplayTree<T, A>
200where
201 T: LazyMapMonoid,
202 A: Allocator<ImplicitSplayTreeNode<T>>,
203{
204 fn drop(&mut self) {
205 unsafe {
206 if let Some(root) = self.root.take() {
207 root.into_dying().drop_all(self.allocator.deref_mut());
208 }
209 ManuallyDrop::drop(&mut self.allocator);
210 }
211 }
212}
213
214impl<T> ImplicitSplayTree<T>
215where
216 T: LazyMapMonoid,
217{
218 pub fn new() -> Self {
219 Self::default()
220 }
221
222 pub fn with_capacity(capacity: usize) -> Self {
223 Self {
224 root: None,
225 length: 0,
226 allocator: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
227 _marker: PhantomData,
228 }
229 }
230}
231
232impl<T, A> ImplicitSplayTree<T, A>
233where
234 T: LazyMapMonoid,
235 A: Allocator<ImplicitSplayTreeNode<T>>,
236{
237 fn node(&mut self, key: T::Key) -> ImplicitSplayTreeRoot<T> {
238 BstRoot::from_data(
239 ImplicitSplayTreeData {
240 value: LazyMapElement::from_key(key),
241 size: 1,
242 rev: false,
243 },
244 self.allocator.deref_mut(),
245 )
246 }
247
248 #[inline]
249 fn splay<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
250 where
251 Seeker: BstSeeker<Spec = ImplicitSplayTreeSpec<T>>,
252 {
253 let (ordering, root) = splay_operations::splay(self.root.take()?, seeker);
254 self.root = Some(root);
255 Some(ordering)
256 }
257
258 pub fn len(&self) -> usize {
259 self.length
260 }
261
262 pub fn is_empty(&self) -> bool {
263 self.length == 0
264 }
265
266 pub fn update<R>(&mut self, range: R, act: T::Act)
267 where
268 R: RangeBounds<usize>,
269 {
270 let mut split = Split3::seek_by_size(&mut self.root, range);
271 if let Some(root) = split.mid_datamut() {
272 ImplicitSplayTreeSpec::update_act(root, &act);
273 }
274 }
275
276 pub fn fold<R>(&mut self, range: R) -> T::Agg
277 where
278 R: RangeBounds<usize>,
279 {
280 let split = Split3::seek_by_size(&mut self.root, range);
281 split
282 .mid()
283 .map(|node| node.into_data().value.agg.clone())
284 .unwrap_or_else(T::agg_unit)
285 }
286
287 pub fn reverse<R>(&mut self, range: R)
288 where
289 R: RangeBounds<usize>,
290 {
291 let mut split = Split3::seek_by_size(&mut self.root, range);
292 if let Some(root) = split.mid_datamut() {
293 ImplicitSplayTreeSpec::reverse(root);
294 }
295 }
296
297 pub fn get(&mut self, index: usize) -> Option<&T::Key> {
298 if index >= self.length {
299 return None;
300 }
301 self.splay(SeekBySize::new(index));
302 Some(&self.root.as_ref()?.reborrow().into_data().value.key)
303 }
304
305 pub fn modify<F>(&mut self, index: usize, f: F)
306 where
307 F: FnOnce(&T::Key) -> T::Key,
308 {
309 assert!(index < self.length);
310 self.splay(SeekBySize::new(index));
311 let mut root = self.root.as_mut().unwrap().borrow_datamut();
312 ImplicitSplayTreeSpec::top_down(root.reborrow_datamut());
313 {
314 let data = root.data_mut();
315 data.value.key = f(&data.value.key);
316 }
317 ImplicitSplayTreeSpec::bottom_up(root);
318 }
319
320 pub fn insert(&mut self, index: usize, key: T::Key) {
321 assert!(index <= self.length);
322 let mut node = self.node(key);
323 if self.root.is_none() {
324 self.root = Some(node);
325 } else if index == self.length {
326 self.splay(SeekBySize::new(index));
327 unsafe { node.borrow_mut().left_mut().set(self.root.take().unwrap()) };
328 ImplicitSplayTreeSpec::bottom_up(node.borrow_datamut());
329 self.root = Some(node);
330 } else {
331 self.splay(SeekBySize::new(index));
332 let mut root = self.root.take().unwrap();
333 let left = unsafe { root.borrow_mut().left_mut().take() };
334 if let Some(left) = left {
335 unsafe { node.borrow_mut().left_mut().set(left) };
336 }
337 ImplicitSplayTreeSpec::bottom_up(root.borrow_datamut());
338 unsafe { node.borrow_mut().right_mut().set(root) };
339 ImplicitSplayTreeSpec::bottom_up(node.borrow_datamut());
340 self.root = Some(node);
341 }
342 self.length += 1;
343 }
344
345 pub fn remove(&mut self, index: usize) -> Option<T::Key> {
346 if index >= self.length {
347 return None;
348 }
349 self.splay(SeekBySize::new(index));
350 let mut node = self.root.take().unwrap();
351 ImplicitSplayTreeSpec::top_down(node.borrow_datamut());
352 let left = unsafe { node.borrow_mut().left_mut().take() };
353 let right = unsafe { node.borrow_mut().right_mut().take() };
354 self.root = ImplicitSplayTreeSpec::merge(left, right);
355 self.length -= 1;
356 let data = unsafe { node.into_dying().into_data(self.allocator.deref_mut()) };
357 Some(data.value.key)
358 }
359
360 pub fn partition_point_acc<F>(&mut self, left: usize, mut pred: F) -> usize
361 where
362 F: FnMut(&T::Agg) -> bool,
363 {
364 let mut split3 = Split3::seek_by_size(&mut self.root, left..);
365 let front_size = split3
366 .left()
367 .map(|node| node.into_data().size)
368 .unwrap_or_default();
369 let split = split3.split_mid(SeekByAccCond::new(|acc| !pred(acc)), EqualSide::Right);
370 let index = split
371 .left()
372 .map(|node| node.into_data().size)
373 .unwrap_or_default();
374 front_size + index
375 }
376
377 pub fn rpartition_point_acc<F>(&mut self, right: usize, mut pred: F) -> usize
378 where
379 F: FnMut(&T::Agg) -> bool,
380 {
381 let mut split3 = Split3::seek_by_size(&mut self.root, ..right);
382 let split = split3.split_mid(SeekByRaccCond::new(|acc| !pred(acc)), EqualSide::Left);
383 split
384 .left()
385 .map(|node| node.into_data().size)
386 .unwrap_or_default()
387 }
388
389 pub fn rotate_left(&mut self, mid: usize) {
390 assert!(mid <= self.length);
391 if mid == 0 || mid == self.length {
392 return;
393 }
394 let (left, right) =
395 ImplicitSplayTreeSpec::split(self.root.take(), SeekBySize::new(mid), EqualSide::Right);
396 self.root = ImplicitSplayTreeSpec::merge(right, left);
397 }
398
399 pub fn rotate_right(&mut self, k: usize) {
400 assert!(k <= self.length);
401 self.rotate_left(self.length - k);
402 }
403}
404
405impl<T, A> Extend<T::Key> for ImplicitSplayTree<T, A>
406where
407 T: LazyMapMonoid,
408 A: Allocator<ImplicitSplayTreeNode<T>>,
409{
410 fn extend<I>(&mut self, iter: I)
411 where
412 I: IntoIterator<Item = T::Key>,
413 {
414 let nodes = iter
415 .into_iter()
416 .map(|key| self.node(key))
417 .collect::<Vec<_>>();
418 let len = nodes.len();
419 let root = if len == 0 {
420 None
421 } else {
422 let mut stack = Vec::with_capacity(64);
423 stack.push((0, len, None::<(usize, usize)>, false));
424 while let Some((start, end, parent, visited)) = stack.pop() {
425 if start == end {
426 continue;
427 }
428 let mid = start + (end - start) / 2;
429 if visited {
430 ImplicitSplayTreeSpec::bottom_up(
431 BstRoot::new(nodes[mid].node).borrow_datamut(),
432 );
433 continue;
434 }
435 if let Some((parent, direction)) = parent {
436 let mut parent = nodes[parent].node;
437 unsafe { parent.as_mut().child[direction] = Some(nodes[mid].node) };
438 }
439 stack.push((start, end, parent, true));
440 stack.push((mid + 1, end, Some((mid, 1)), false));
441 stack.push((start, mid, Some((mid, 0)), false));
442 }
443 Some(BstRoot::new(nodes[len / 2].node))
444 };
445 self.root = ImplicitSplayTreeSpec::merge(self.root.take(), root);
446 self.length += len;
447 }crates/competitive/src/data_structure/implicit_treap.rs (line 94)
84 fn update_act(mut node: BstDataMutRef<'_, Self>, act: &T::Act) {
85 if T::is_act_unit(act) {
86 return;
87 }
88 T::act_operate_assign(&mut node.data_mut().value.act, act);
89 node.data_mut().value.key = T::act_key(&node.reborrow().into_data().value.key, act);
90 if let Some(agg) = T::act_agg(&node.reborrow().into_data().value.agg, act) {
91 node.data_mut().value.agg = agg;
92 } else {
93 Self::top_down(node.reborrow_datamut());
94 Self::bottom_up(node);
95 }
96 }
97
98 fn reverse(mut node: BstDataMutRef<'_, Self>) {
99 node.swap_children();
100 let data = node.data_mut();
101 T::toggle(&mut data.value.agg);
102 data.rev ^= true;
103 }
104}
105
106impl<T> BstSpec for ImplicitTreapSpec<T>
107where
108 T: LazyMapMonoid,
109{
110 type Parent = WithNoParent<Self::Data>;
111 type Data = ImplicitTreapData<T>;
112
113 fn top_down(mut node: BstDataMutRef<'_, Self>) {
114 if !T::is_act_unit(&node.reborrow().into_data().value.act) {
115 let act = replace(&mut node.data_mut().value.act, T::act_unit());
116 if let Ok(left) = node.reborrow_datamut().left().descend() {
117 Self::update_act(left, &act);
118 }
119 if let Ok(right) = node.reborrow_datamut().right().descend() {
120 Self::update_act(right, &act);
121 }
122 }
123 if node.reborrow().into_data().rev {
124 node.data_mut().rev = false;
125 if let Ok(left) = node.reborrow_datamut().left().descend() {
126 Self::reverse(left);
127 }
128 if let Ok(right) = node.reborrow_datamut().right().descend() {
129 Self::reverse(right);
130 }
131 }
132 }
133
134 fn bottom_up(mut node: BstDataMutRef<'_, Self>) {
135 let mut agg = T::single_agg(&node.reborrow().into_data().value.key);
136 let mut size = 1;
137 if let Ok(left) = node.reborrow().left().descend() {
138 let data = left.into_data();
139 agg = T::agg_operate(&data.value.agg, &agg);
140 size += data.size;
141 }
142 if let Ok(right) = node.reborrow().right().descend() {
143 let data = right.into_data();
144 agg = T::agg_operate(&agg, &data.value.agg);
145 size += data.size;
146 }
147 let data = node.data_mut();
148 data.value.agg = agg;
149 data.size = size;
150 }
151
152 fn merge(
153 left: Option<ImplicitTreapRoot<T>>,
154 right: Option<ImplicitTreapRoot<T>>,
155 ) -> Option<ImplicitTreapRoot<T>> {
156 match (left, right) {
157 (None, None) => None,
158 (None, Some(node)) | (Some(node), None) => Some(node),
159 (Some(mut left), Some(mut right)) => unsafe {
160 if left.reborrow().into_data().priority > right.reborrow().into_data().priority {
161 Self::top_down(left.borrow_datamut());
162 let lr = left.borrow_mut().right().take();
163 let lr = Self::merge(lr, Some(right)).unwrap_unchecked();
164 left.borrow_mut().right().set(lr);
165 Self::bottom_up(left.borrow_datamut());
166 Some(left)
167 } else {
168 Self::top_down(right.borrow_datamut());
169 let rl = right.borrow_mut().left().take();
170 let rl = Self::merge(Some(left), rl).unwrap_unchecked();
171 right.borrow_mut().left().set(rl);
172 Self::bottom_up(right.borrow_datamut());
173 Some(right)
174 }
175 },
176 }
177 }
178
179 fn split<Seeker>(
180 node: Option<ImplicitTreapRoot<T>>,
181 mut seeker: Seeker,
182 equal_side: EqualSide,
183 ) -> (Option<ImplicitTreapRoot<T>>, Option<ImplicitTreapRoot<T>>)
184 where
185 Seeker: BstSeeker<Spec = Self>,
186 {
187 match node {
188 None => (None, None),
189 Some(mut node) => {
190 Self::top_down(node.borrow_datamut());
191 if equal_side.goes_left(seeker.bst_seek(node.reborrow())) {
192 unsafe {
193 let right = node.borrow_mut().right().take();
194 let (l, r) = Self::split(right, seeker, equal_side);
195 if let Some(l) = l {
196 node.borrow_mut().right().set(l);
197 }
198 Self::bottom_up(node.borrow_datamut());
199 (Some(node), r)
200 }
201 } else {
202 unsafe {
203 let left = node.borrow_mut().left().take();
204 let (l, r) = Self::split(left, seeker, equal_side);
205 if let Some(r) = r {
206 node.borrow_mut().left().set(r);
207 }
208 Self::bottom_up(node.borrow_datamut());
209 (l, Some(node))
210 }
211 }
212 }
213 }
214 }
215}
216
217pub struct ImplicitTreap<T, A = MemoryPool<ImplicitTreapNode<T>>>
218where
219 T: LazyMapMonoid,
220 A: Allocator<ImplicitTreapNode<T>>,
221{
222 root: Option<ImplicitTreapRoot<T>>,
223 length: usize,
224 rng: Xorshift,
225 allocator: ManuallyDrop<A>,
226 _marker: PhantomData<fn() -> T>,
227}
228
229impl<T, A> Default for ImplicitTreap<T, A>
230where
231 T: LazyMapMonoid,
232 A: Allocator<ImplicitTreapNode<T>> + Default,
233{
234 fn default() -> Self {
235 Self {
236 root: None,
237 length: 0,
238 rng: Xorshift::new(),
239 allocator: ManuallyDrop::new(A::default()),
240 _marker: PhantomData,
241 }
242 }
243}
244
245impl<T, A> Drop for ImplicitTreap<T, A>
246where
247 T: LazyMapMonoid,
248 A: Allocator<ImplicitTreapNode<T>>,
249{
250 fn drop(&mut self) {
251 unsafe {
252 if let Some(root) = self.root.take() {
253 root.into_dying().drop_all(self.allocator.deref_mut());
254 }
255 ManuallyDrop::drop(&mut self.allocator);
256 }
257 }
258}
259
260impl<T> ImplicitTreap<T>
261where
262 T: LazyMapMonoid,
263{
264 pub fn new() -> Self {
265 Self::default()
266 }
267
268 pub fn with_capacity(capacity: usize) -> Self {
269 Self {
270 root: None,
271 length: 0,
272 rng: Xorshift::new(),
273 allocator: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
274 _marker: PhantomData,
275 }
276 }
277}
278
279impl<T, A> ImplicitTreap<T, A>
280where
281 T: LazyMapMonoid,
282 A: Allocator<ImplicitTreapNode<T>>,
283{
284 fn node(&mut self, key: T::Key) -> ImplicitTreapRoot<T> {
285 BstRoot::from_data(
286 ImplicitTreapData {
287 priority: self.rng.rand64(),
288 value: LazyMapElement::from_key(key),
289 size: 1,
290 rev: false,
291 },
292 self.allocator.deref_mut(),
293 )
294 }
295
296 fn build<I>(&mut self, iter: I) -> (Option<ImplicitTreapRoot<T>>, usize)
297 where
298 I: IntoIterator<Item = T::Key>,
299 {
300 let mut stack = vec![];
301 let mut len = 0;
302 for key in iter {
303 let mut cur = self.node(key).node;
304 let mut left = None;
305 unsafe {
306 while stack
307 .last()
308 .is_some_and(|node: &NonNull<ImplicitTreapNode<T>>| {
309 node.as_ref().data.priority < cur.as_ref().data.priority
310 })
311 {
312 left = stack.pop();
313 }
314 cur.as_mut().child[0] = left;
315 if let Some(parent) = stack.last_mut() {
316 parent.as_mut().child[1] = Some(cur);
317 }
318 }
319 stack.push(cur);
320 len += 1;
321 }
322 let root = stack.first().copied().map(BstRoot::new);
323 if let Some(mut root) = root {
324 Self::build_bottom_up(root.borrow_datamut());
325 (Some(root), len)
326 } else {
327 (None, len)
328 }
329 }
330
331 fn build_bottom_up(mut node: BstDataMutRef<'_, ImplicitTreapSpec<T>>) {
332 if let Ok(left) = node.reborrow_datamut().left().descend() {
333 Self::build_bottom_up(left);
334 }
335 if let Ok(right) = node.reborrow_datamut().right().descend() {
336 Self::build_bottom_up(right);
337 }
338 ImplicitTreapSpec::<T>::bottom_up(node);
339 }
340
341 pub fn len(&self) -> usize {
342 self.length
343 }
344
345 pub fn is_empty(&self) -> bool {
346 self.length == 0
347 }
348
349 pub fn update<R>(&mut self, range: R, x: T::Act)
350 where
351 R: RangeBounds<usize>,
352 {
353 let mut split = Split3::seek_by_size(&mut self.root, range);
354 if let Some(root) = split.mid_datamut() {
355 ImplicitTreapSpec::<T>::update_act(root, &x);
356 }
357 }
358
359 pub fn fold<R>(&mut self, range: R) -> T::Agg
360 where
361 R: RangeBounds<usize>,
362 {
363 let split = Split3::seek_by_size(&mut self.root, range);
364 split
365 .mid()
366 .map(|node| node.into_data().value.agg.clone())
367 .unwrap_or_else(T::agg_unit)
368 }
369
370 pub fn reverse<R>(&mut self, range: R)
371 where
372 R: RangeBounds<usize>,
373 {
374 let mut split = Split3::seek_by_size(&mut self.root, range);
375 if let Some(root) = split.mid_datamut() {
376 ImplicitTreapSpec::<T>::reverse(root);
377 }
378 }
379
380 pub fn get(&mut self, index: usize) -> Option<&T::Key> {
381 if index >= self.length {
382 return None;
383 }
384 let split = Split3::seek_by_size(&mut self.root, index..=index);
385 let node = split.mid()?.node;
386 drop(split);
387 Some(unsafe { &(*node.as_ptr()).data.value.key })
388 }
389
390 pub fn modify<F>(&mut self, index: usize, f: F)
391 where
392 F: FnOnce(&T::Key) -> T::Key,
393 {
394 assert!(index < self.length);
395 let mut split = Split3::seek_by_size(&mut self.root, index..=index);
396 let mut node = split.mid_datamut().unwrap();
397 ImplicitTreapSpec::<T>::top_down(node.reborrow_datamut());
398 {
399 let data = node.data_mut();
400 data.value.key = f(&data.value.key);
401 }
402 ImplicitTreapSpec::<T>::bottom_up(node);
403 }crates/competitive/src/data_structure/splay_operations.rs (line 65)
53 pub unsafe fn rotate<Spec, Data>(mut node: NodePtr<Spec>)
54 where
55 Spec: BstSpec<Data = Data, Parent = WithParent<Data>>,
56 {
57 let (parent, direction) = unsafe { internal_parent::<Spec, Data>(node) }
58 .expect("an auxiliary root cannot be rotated");
59 unsafe {
60 node.as_mut().parent.parent = parent.as_ref().parent.parent;
61 if let Ok((mut grandparent, direction)) = internal_parent::<Spec, Data>(parent) {
62 grandparent.as_mut().child[direction] = Some(node);
63 }
64 rotate_at::<Spec, Data>(node, parent, direction);
65 Spec::bottom_up(BstDataMutRef::new_unchecked(parent));
66 }
67 }
68
69 /// Moves `node` to the root of its auxiliary tree and returns the previous root.
70 ///
71 /// # Safety
72 ///
73 /// `node` and every pointer reachable through its auxiliary-parent chain must
74 /// refer to live nodes of the same tree.
75 #[inline(always)]
76 pub unsafe fn splay<Spec, Data>(node: NodePtr<Spec>) -> NodePtr<Spec>
77 where
78 Spec: BstSpec<Data = Data, Parent = WithParent<Data>>,
79 {
80 let mut inline_stack = [const { MaybeUninit::uninit() }; 64];
81 let mut inline_len = 0;
82 let mut overflow_stack = Vec::new();
83 let mut current = node;
84 loop {
85 if inline_len < inline_stack.len() {
86 inline_stack[inline_len].write(current);
87 inline_len += 1;
88 } else {
89 overflow_stack.push(current);
90 }
91 match unsafe { internal_parent::<Spec, Data>(current) } {
92 Ok((parent, _)) => current = parent,
93 Err(_) => break,
94 }
95 }
96 for &node in overflow_stack.iter().rev() {
97 unsafe { Spec::top_down(BstDataMutRef::new_unchecked(node)) };
98 }
99 while inline_len > 0 {
100 inline_len -= 1;
101 unsafe {
102 Spec::top_down(BstDataMutRef::new_unchecked(
103 *inline_stack[inline_len].assume_init_ref(),
104 ));
105 }
106 }
107
108 while let Ok((parent, node_direction)) = unsafe { internal_parent::<Spec, Data>(node) } {
109 if let Ok((_, parent_direction)) = unsafe { internal_parent::<Spec, Data>(parent) } {
110 if node_direction == parent_direction {
111 unsafe { rotate::<Spec, Data>(parent) };
112 } else {
113 unsafe { rotate::<Spec, Data>(node) };
114 }
115 }
116 unsafe { rotate::<Spec, Data>(node) };
117 }
118 unsafe { Spec::bottom_up(BstDataMutRef::new_unchecked(node)) };
119 current
120 }
121
122 /// Moves `node` to the root by propagating only the nodes involved in each rotation and
123 /// returns the previous root.
124 ///
125 /// # Safety
126 ///
127 /// `node` and every pointer reachable through its auxiliary-parent chain must refer to live
128 /// nodes of the same tree. Propagating an ancestor after its descendant must be valid for
129 /// `Spec`.
130 #[inline(always)]
131 pub unsafe fn splay_with_local_top_down<Spec, Data>(mut node: NodePtr<Spec>) -> NodePtr<Spec>
132 where
133 Spec: BstSpec<Data = Data, Parent = WithParent<Data>>,
134 {
135 let mut current = node;
136 unsafe { Spec::top_down(BstDataMutRef::new_unchecked(node)) };
137 while let Ok((parent, _)) = unsafe { internal_parent::<Spec, Data>(node) } {
138 match unsafe { internal_parent::<Spec, Data>(parent) } {
139 Ok((grandparent, _)) => {
140 current = grandparent;
141 unsafe {
142 Spec::top_down(BstDataMutRef::new_unchecked(grandparent));
143 Spec::top_down(BstDataMutRef::new_unchecked(parent));
144 Spec::top_down(BstDataMutRef::new_unchecked(node));
145 let node_direction = usize::from(parent.as_ref().child[1] == Some(node));
146 let parent_direction =
147 usize::from(grandparent.as_ref().child[1] == Some(parent));
148 node.as_mut().parent.parent = grandparent.as_ref().parent.parent;
149 if let Ok((mut ancestor, direction)) =
150 internal_parent::<Spec, Data>(grandparent)
151 {
152 ancestor.as_mut().child[direction] = Some(node);
153 }
154 if node_direction == parent_direction {
155 rotate_at::<Spec, Data>(parent, grandparent, parent_direction);
156 rotate_at::<Spec, Data>(node, parent, node_direction);
157 Spec::bottom_up(BstDataMutRef::new_unchecked(grandparent));
158 Spec::bottom_up(BstDataMutRef::new_unchecked(parent));
159 } else {
160 rotate_at::<Spec, Data>(node, parent, node_direction);
161 rotate_at::<Spec, Data>(node, grandparent, parent_direction);
162 Spec::bottom_up(BstDataMutRef::new_unchecked(parent));
163 Spec::bottom_up(BstDataMutRef::new_unchecked(grandparent));
164 }
165 }
166 }
167 Err(ancestor) => {
168 current = parent;
169 unsafe {
170 Spec::top_down(BstDataMutRef::new_unchecked(parent));
171 Spec::top_down(BstDataMutRef::new_unchecked(node));
172 let direction = usize::from(parent.as_ref().child[1] == Some(node));
173 node.as_mut().parent.parent = ancestor;
174 rotate_at::<Spec, Data>(node, parent, direction);
175 Spec::bottom_up(BstDataMutRef::new_unchecked(parent));
176 }
177 }
178 }
179 }
180 unsafe { Spec::bottom_up(BstDataMutRef::new_unchecked(node)) };
181 current
182 }
183}
184
185pub fn rooted_heavy_order(
186 vertices_size: usize,
187 edges: &[(usize, usize)],
188) -> Vec<(usize, usize, bool)> {
189 if vertices_size == 0 {
190 return Vec::new();
191 }
192 let mut head = vec![usize::MAX; vertices_size];
193 let mut to = Vec::with_capacity(edges.len() * 2);
194 let mut next = Vec::with_capacity(edges.len() * 2);
195 for &(u, v) in edges {
196 to.push(v);
197 next.push(head[u]);
198 head[u] = to.len() - 1;
199 to.push(u);
200 next.push(head[v]);
201 head[v] = to.len() - 1;
202 }
203 let mut parent = vec![usize::MAX; vertices_size];
204 let mut stack = vec![0];
205 let mut order = Vec::with_capacity(vertices_size - 1);
206 parent[0] = 0;
207 while let Some(u) = stack.pop() {
208 let mut edge = head[u];
209 while edge != usize::MAX {
210 let v = to[edge];
211 if parent[v] == usize::MAX {
212 parent[v] = u;
213 order.push((v, u));
214 stack.push(v);
215 }
216 edge = next[edge];
217 }
218 }
219 let mut size = vec![1usize; vertices_size];
220 let mut heavy = vec![usize::MAX; vertices_size];
221 for &(child, parent) in order.iter().rev() {
222 size[parent] += size[child];
223 if heavy[parent] == usize::MAX || size[heavy[parent]] < size[child] {
224 heavy[parent] = child;
225 }
226 }
227 order
228 .into_iter()
229 .map(|(child, parent)| (child, parent, heavy[parent] == child))
230 .collect()
231}
232
233#[inline]
234pub fn splay<Spec, Data, Seeker>(
235 root: BstRoot<Spec>,
236 mut seeker: Seeker,
237) -> (Ordering, BstRoot<Spec>)
238where
239 Spec: BstSpec<Data = Data, Parent = WithNoParent<Data>>,
240 Seeker: BstSeeker<Spec = Spec>,
241{
242 let mut root = root;
243 let mut left_subtree = None;
244 let mut right_subtree = None;
245 let mut left_entry = &mut left_subtree;
246 let mut right_entry = &mut right_subtree;
247 let mut inline_stack = [None; 24];
248 let mut inline_len = 0;
249 let mut overflow_stack = vec![];
250
251 macro_rules! push_node {
252 ($node:expr) => {
253 if inline_len < inline_stack.len() {
254 inline_stack[inline_len] = Some($node);
255 inline_len += 1;
256 } else {
257 overflow_stack.push($node);
258 }
259 };
260 }
261
262 macro_rules! add {
263 (@left $node:ident) => {
264 *left_entry = Some($node.node);
265 push_node!($node.node);
266 left_entry = unsafe { &mut $node.node.as_mut().child[1] };
267 };
268 (@right $node:ident) => {
269 *right_entry = Some($node.node);
270 push_node!($node.node);
271 right_entry = unsafe { &mut $node.node.as_mut().child[0] };
272 };
273 }
274
275 let root_ordering = loop {
276 Spec::top_down(root.borrow_datamut());
277 match seeker.bst_seek(root.reborrow()) {
278 Ordering::Greater => {
279 let Some(mut child) = (unsafe { root.borrow_mut().left_mut().take() }) else {
280 break Ordering::Greater;
281 };
282 Spec::top_down(child.borrow_datamut());
283 match seeker.bst_seek(child.reborrow()) {
284 Ordering::Greater => {
285 let Some(mut grandchild) =
286 (unsafe { child.borrow_mut().left_mut().take() })
287 else {
288 add!(@right root);
289 root = child;
290 break Ordering::Greater;
291 };
292 Spec::top_down(grandchild.borrow_datamut());
293 let child_right = unsafe { child.borrow_mut().right_mut().take() };
294 if let Some(child_right) = child_right {
295 unsafe { root.borrow_mut().left_mut().set(child_right) };
296 }
297 Spec::bottom_up(root.borrow_datamut());
298 unsafe { child.borrow_mut().right_mut().set(root) };
299 add!(@right child);
300 root = grandchild;
301 }
302 Ordering::Equal => {
303 add!(@right root);
304 root = child;
305 break Ordering::Equal;
306 }
307 Ordering::Less => {
308 let Some(mut grandchild) =
309 (unsafe { child.borrow_mut().right_mut().take() })
310 else {
311 add!(@right root);
312 root = child;
313 break Ordering::Less;
314 };
315 Spec::top_down(grandchild.borrow_datamut());
316 add!(@right root);
317 add!(@left child);
318 root = grandchild;
319 }
320 }
321 }
322 Ordering::Equal => break Ordering::Equal,
323 Ordering::Less => {
324 let Some(mut child) = (unsafe { root.borrow_mut().right_mut().take() }) else {
325 break Ordering::Less;
326 };
327 Spec::top_down(child.borrow_datamut());
328 match seeker.bst_seek(child.reborrow()) {
329 Ordering::Greater => {
330 let Some(mut grandchild) =
331 (unsafe { child.borrow_mut().left_mut().take() })
332 else {
333 add!(@left root);
334 root = child;
335 break Ordering::Greater;
336 };
337 Spec::top_down(grandchild.borrow_datamut());
338 add!(@left root);
339 add!(@right child);
340 root = grandchild;
341 }
342 Ordering::Equal => {
343 add!(@left root);
344 root = child;
345 break Ordering::Equal;
346 }
347 Ordering::Less => {
348 let Some(mut grandchild) =
349 (unsafe { child.borrow_mut().right_mut().take() })
350 else {
351 add!(@left root);
352 root = child;
353 break Ordering::Less;
354 };
355 Spec::top_down(grandchild.borrow_datamut());
356 let child_left = unsafe { child.borrow_mut().left_mut().take() };
357 if let Some(child_left) = child_left {
358 unsafe { root.borrow_mut().right_mut().set(child_left) };
359 }
360 Spec::bottom_up(root.borrow_datamut());
361 unsafe { child.borrow_mut().left_mut().set(root) };
362 add!(@left child);
363 root = grandchild;
364 }
365 }
366 }
367 }
368 };
369
370 *left_entry = unsafe { root.borrow_mut().left_mut().take() }.map(|node| node.node);
371 *right_entry = unsafe { root.borrow_mut().right_mut().take() }.map(|node| node.node);
372 unsafe {
373 root.node.as_mut().child[0] = left_subtree;
374 root.node.as_mut().child[1] = right_subtree;
375 while let Some(node) = overflow_stack.pop() {
376 Spec::bottom_up(BstRoot::new(node).borrow_datamut());
377 }
378 while inline_len > 0 {
379 inline_len -= 1;
380 let node = inline_stack[inline_len].unwrap_unchecked();
381 Spec::bottom_up(BstRoot::new(node).borrow_datamut());
382 }
383 }
384 Spec::bottom_up(root.borrow_datamut());
385 (root_ordering, root)
386}
387
388#[inline]
389pub fn merge<Spec, Data>(
390 left: Option<BstRoot<Spec>>,
391 right: Option<BstRoot<Spec>>,
392) -> Option<BstRoot<Spec>>
393where
394 Spec: BstSpec<Data = Data, Parent = WithNoParent<Data>>,
395{
396 match (left, right) {
397 (None, None) => None,
398 (None, Some(root)) | (Some(root), None) => Some(root),
399 (Some(left), Some(mut right)) if right.reborrow().left().descend().is_err() => {
400 Spec::top_down(right.borrow_datamut());
401 unsafe { right.borrow_mut().left_mut().set(left) };
402 Spec::bottom_up(right.borrow_datamut());
403 Some(right)
404 }
405 (Some(left), Some(right)) => {
406 let (_, mut root) = splay(left, SeekRight::default());
407 unsafe { root.borrow_mut().right_mut().set(right) };
408 Spec::bottom_up(root.borrow_datamut());
409 Some(root)
410 }
411 }
412}
413
414#[inline]
415pub fn split<Spec, Data, Seeker>(
416 root: Option<BstRoot<Spec>>,
417 seeker: Seeker,
418 equal_side: EqualSide,
419) -> (Option<BstRoot<Spec>>, Option<BstRoot<Spec>>)
420where
421 Spec: BstSpec<Data = Data, Parent = WithNoParent<Data>>,
422 Seeker: BstSeeker<Spec = Spec>,
423{
424 let Some(root) = root else {
425 return (None, None);
426 };
427 let (ordering, mut root) = splay(root, seeker);
428 if equal_side.goes_left(ordering) {
429 let right = unsafe { root.borrow_mut().right_mut().take() };
430 Spec::bottom_up(root.borrow_datamut());
431 (Some(root), right)
432 } else {
433 let left = unsafe { root.borrow_mut().left_mut().take() };
434 Spec::bottom_up(root.borrow_datamut());
435 (left, Some(root))
436 }
437}Additional examples can be found in:
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".