pub struct BstNodeRef<BorrowType, Spec>where
Spec: BstSpec,{
pub node: NonNull<BstNode<Spec::Data, Spec::Parent>>,
_marker: PhantomData<BorrowType>,
}Fields§
§node: NonNull<BstNode<Spec::Data, Spec::Parent>>§_marker: PhantomData<BorrowType>Implementations§
Source§impl<BorrowType, Spec> BstNodeRef<BorrowType, Spec>where
Spec: BstSpec,
BorrowType: BorrowType,
impl<BorrowType, Spec> BstNodeRef<BorrowType, Spec>where
Spec: BstSpec,
BorrowType: BorrowType,
Sourcepub unsafe fn new_unchecked(
node: NonNull<BstNode<Spec::Data, Spec::Parent>>,
) -> Self
pub unsafe fn new_unchecked( node: NonNull<BstNode<Spec::Data, Spec::Parent>>, ) -> Self
Examples found in repository?
crates/competitive/src/tree/top_tree.rs (line 369)
368 unsafe fn pull_top(node: TopPtr<S, A>) {
369 unsafe { TopBstSpec::<S, A>::bottom_up(BstDataMutRef::new_unchecked(node)) };
370 }
371
372 #[inline]
373 unsafe fn pull_rake(node: RakePtr<S, A>) {
374 unsafe { RakeBstSpec::<S, A>::bottom_up(BstDataMutRef::new_unchecked(node)) };
375 }
376
377 #[inline]
378 unsafe fn splay_top(node: TopPtr<S, A>) {
379 let root = if A::ROOT_TO_NODE_TOP_DOWN {
380 unsafe {
381 splay_operations::with_parent::splay::<TopBstSpec<S, A>, TopTreeData<S, A>>(node)
382 }
383 } else {
384 unsafe {
385 splay_operations::with_parent::splay_with_local_top_down::<
386 TopBstSpec<S, A>,
387 TopTreeData<S, A>,
388 >(node)
389 }
390 };
391 if root != node {
392 unsafe {
393 (*node.as_ptr()).data.belong = (*root.as_ptr()).data.belong.take();
394 }
395 }
396 }
397
398 #[inline]
399 unsafe fn splay_rake(node: RakePtr<S, A>) {
400 unsafe {
401 splay_operations::with_parent::splay_with_local_top_down::<
402 RakeBstSpec<S, A>,
403 RakeData<S, A>,
404 >(node)
405 };
406 }
407
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/tree/link_cut_tree.rs (line 208)
206 unsafe fn pull(node: LinkCutPtr<S>) {
207 unsafe {
208 LinkCutBstSpec::<S>::bottom_up(BstDataMutRef::new_unchecked(node));
209 }
210 }
211
212 #[inline]
213 unsafe fn splay(node: LinkCutPtr<S>) {
214 let root = if S::ROOT_TO_NODE_TOP_DOWN {
215 unsafe {
216 splay_operations::with_parent::splay::<LinkCutBstSpec<S>, LinkCutData<S>>(node)
217 }
218 } else {
219 unsafe {
220 splay_operations::with_parent::splay_with_local_top_down::<
221 LinkCutBstSpec<S>,
222 LinkCutData<S>,
223 >(node)
224 }
225 };
226 if root != node {
227 unsafe {
228 LinkCutBstSpec::<S>::with_two_inner_mut(root, node, S::transfer_path_parent);
229 }
230 }
231 }
232
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/binary_search_tree/node_id.rs (line 57)
53 pub unsafe fn reborrow<'a>(
54 self,
55 _root: &'a Option<BstRoot<Spec>>,
56 ) -> BstNodeRef<node::marker::Immut<'a>, Spec> {
57 unsafe { BstNodeRef::new_unchecked(self.node) }
58 }
59
60 pub unsafe fn reborrow_datamut<'a>(
61 self,
62 _root: &'a mut Option<BstRoot<Spec>>,
63 ) -> BstNodeRef<node::marker::DataMut<'a>, Spec> {
64 unsafe { BstNodeRef::new_unchecked(self.node) }
65 }
66
67 pub unsafe fn reborrow_mut<'a>(
68 self,
69 _root: &'a mut Option<BstRoot<Spec>>,
70 ) -> BstNodeRef<node::marker::Mut<'a>, Spec> {
71 unsafe { BstNodeRef::new_unchecked(self.node) }
72 }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 }Sourcepub fn reborrow(&self) -> BstNodeRef<Immut<'_>, Spec>
pub fn reborrow(&self) -> BstNodeRef<Immut<'_>, Spec>
Examples found in repository?
crates/competitive/src/data_structure/binary_search_tree/split.rs (line 41)
40 pub fn left(&self) -> Option<BstImmutRef<'_, Spec>> {
41 self.left.as_ref().map(|node| node.reborrow())
42 }
43
44 pub fn right(&self) -> Option<BstImmutRef<'_, Spec>> {
45 self.right.as_ref().map(|node| node.reborrow())
46 }
47
48 pub fn left_datamut(&mut self) -> Option<BstDataMutRef<'_, Spec>> {
49 self.left.as_mut().map(|node| node.borrow_datamut())
50 }
51
52 pub fn right_datamut(&mut self) -> Option<BstDataMutRef<'_, Spec>> {
53 self.right.as_mut().map(|node| node.borrow_datamut())
54 }
55
56 pub fn manually_merge<F>(&mut self, mut f: F)
57 where
58 F: FnMut(Option<BstRoot<Spec>>, Option<BstRoot<Spec>>) -> Option<BstRoot<Spec>>,
59 {
60 self.left = f(self.left.take(), self.right.take());
61 }
62}
63
64impl<'a, Spec> Drop for Split<'a, Spec>
65where
66 Spec: BstSpec,
67{
68 fn drop(&mut self) {
69 *self.root = Spec::merge(self.left.take(), self.right.take());
70 }
71}
72
73pub struct Split3<'a, Spec>
74where
75 Spec: BstSpec,
76{
77 left: Option<BstRoot<Spec>>,
78 mid: Option<BstRoot<Spec>>,
79 right: Option<BstRoot<Spec>>,
80 root: &'a mut Option<BstRoot<Spec>>,
81}
82
83impl<'a, Spec> Split3<'a, Spec>
84where
85 Spec: BstSpec,
86{
87 pub fn new<Seek1, Seek2>(
88 node: &'a mut Option<BstRoot<Spec>>,
89 start: Bound<Seek1>,
90 end: Bound<Seek2>,
91 ) -> Self
92 where
93 Seek1: BstSeeker<Spec = Spec>,
94 Seek2: BstSeeker<Spec = Spec>,
95 {
96 let (mut rest, right) = match end {
97 Bound::Included(seeker) => Spec::split(node.take(), seeker, EqualSide::Left),
98 Bound::Excluded(seeker) => Spec::split(node.take(), seeker, EqualSide::Right),
99 Bound::Unbounded => (node.take(), None),
100 };
101 let (left, mid) = match start {
102 Bound::Included(seeker) => Spec::split(rest.take(), seeker, EqualSide::Right),
103 Bound::Excluded(seeker) => Spec::split(rest.take(), seeker, EqualSide::Left),
104 Bound::Unbounded => (None, rest),
105 };
106 Self {
107 left,
108 mid,
109 right,
110 root: node,
111 }
112 }
113
114 pub fn left(&self) -> Option<BstImmutRef<'_, Spec>> {
115 self.left.as_ref().map(|node| node.reborrow())
116 }
117
118 pub fn mid(&self) -> Option<BstImmutRef<'_, Spec>> {
119 self.mid.as_ref().map(|node| node.reborrow())
120 }
121
122 pub fn right(&self) -> Option<BstImmutRef<'_, Spec>> {
123 self.right.as_ref().map(|node| node.reborrow())
124 }More examples
crates/competitive/src/data_structure/binary_search_tree/seeker.rs (line 29)
28 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
29 if node.reborrow().left().descend().is_ok() {
30 Ordering::Greater
31 } else {
32 Ordering::Equal
33 }
34 }
35}
36
37pub struct SeekRight<Spec> {
38 _marker: PhantomData<fn() -> Spec>,
39}
40
41impl<S> Default for SeekRight<S> {
42 fn default() -> Self {
43 Self {
44 _marker: PhantomData,
45 }
46 }
47}
48
49impl<Spec> BstSeeker for SeekRight<Spec>
50where
51 Spec: BstSpec,
52{
53 type Spec = Spec;
54 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
55 if node.reborrow().right().descend().is_ok() {
56 Ordering::Less
57 } else {
58 Ordering::Equal
59 }
60 }
61}
62
63pub struct SeekByKey<'a, Spec, K, Q>
64where
65 Q: ?Sized,
66{
67 key: &'a Q,
68 _marker: PhantomData<fn() -> (Spec, K)>,
69}
70
71impl<'a, Spec, K, Q> SeekByKey<'a, Spec, K, Q>
72where
73 Q: ?Sized,
74{
75 pub fn new(key: &'a Q) -> Self {
76 Self {
77 key,
78 _marker: PhantomData,
79 }
80 }
81}
82
83impl<Spec, K, Q> BstSeeker for SeekByKey<'_, Spec, K, Q>
84where
85 Spec: BstSpec<Data: BstDataAccess<data::marker::Key, Value = K>>,
86 K: Borrow<Q>,
87 Q: Ord + ?Sized,
88{
89 type Spec = Spec;
90
91 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
92 node.reborrow()
93 .into_data()
94 .bst_data()
95 .borrow()
96 .cmp(self.key)
97 }
98}
99
100pub struct SeekBySize<Spec> {
101 index: usize,
102 _marker: PhantomData<fn() -> Spec>,
103}
104
105impl<Spec> SeekBySize<Spec> {
106 pub fn new(index: usize) -> Self {
107 Self {
108 index,
109 _marker: PhantomData,
110 }
111 }
112}
113
114impl<Spec> BstSeeker for SeekBySize<Spec>
115where
116 Spec: BstSpec<Data: BstDataAccess<data::marker::Size, Value = usize>>,
117{
118 type Spec = Spec;
119
120 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
121 let lsize = node
122 .reborrow()
123 .left()
124 .descend()
125 .map(|l| *l.into_data().bst_data())
126 .unwrap_or_default();
127 let ord = lsize.cmp(&self.index);
128 if matches!(ord, Ordering::Less) {
129 self.index -= lsize + 1;
130 }
131 ord
132 }
133}
134
135pub struct SeekByAccCond<Spec, L, F>
136where
137 L: LazyMapMonoid,
138{
139 acc: L::Agg,
140 f: F,
141 _marker: PhantomData<fn() -> (Spec, L)>,
142}
143
144impl<Spec, L, F> SeekByAccCond<Spec, L, F>
145where
146 L: LazyMapMonoid,
147 F: FnMut(&L::Agg) -> bool,
148{
149 pub fn new(f: F) -> Self {
150 Self {
151 acc: L::agg_unit(),
152 f,
153 _marker: PhantomData,
154 }
155 }
156}
157
158impl<Spec, L, F> BstSeeker for SeekByAccCond<Spec, L, F>
159where
160 Spec: BstSpec<Data: BstDataAccess<data::marker::LazyMap, Value = LazyMapElement<L>>>,
161 L: LazyMapMonoid,
162 F: FnMut(&L::Agg) -> bool,
163{
164 type Spec = Spec;
165
166 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
167 if let Ok(left) = node.reborrow().left().descend() {
168 let left_agg = &left.into_data().bst_data().agg;
169 let nagg = L::agg_operate(&self.acc, left_agg);
170 if (self.f)(&nagg) {
171 return Ordering::Greater;
172 }
173 let nagg = L::agg_operate(
174 &nagg,
175 &L::single_agg(&node.reborrow().into_data().bst_data().key),
176 );
177 if (self.f)(&nagg) {
178 Ordering::Equal
179 } else {
180 self.acc = nagg;
181 Ordering::Less
182 }
183 } else {
184 let nagg = L::agg_operate(
185 &self.acc,
186 &L::single_agg(&node.reborrow().into_data().bst_data().key),
187 );
188 if (self.f)(&nagg) {
189 Ordering::Equal
190 } else {
191 self.acc = nagg;
192 Ordering::Less
193 }
194 }
195 }
196}
197
198pub struct SeekByRaccCond<Spec, L, F>
199where
200 L: LazyMapMonoid,
201{
202 acc: L::Agg,
203 f: F,
204 _marker: PhantomData<fn() -> (Spec, L)>,
205}
206
207impl<Spec, L, F> SeekByRaccCond<Spec, L, F>
208where
209 L: LazyMapMonoid,
210 F: FnMut(&L::Agg) -> bool,
211{
212 pub fn new(f: F) -> Self {
213 Self {
214 acc: L::agg_unit(),
215 f,
216 _marker: PhantomData,
217 }
218 }
219}
220
221impl<Spec, L, F> BstSeeker for SeekByRaccCond<Spec, L, F>
222where
223 Spec: BstSpec<Data: BstDataAccess<data::marker::LazyMap, Value = LazyMapElement<L>>>,
224 L: LazyMapMonoid,
225 F: FnMut(&L::Agg) -> bool,
226{
227 type Spec = Spec;
228
229 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
230 if let Ok(right) = node.reborrow().right().descend() {
231 let right_agg = &right.into_data().bst_data().agg;
232 let nagg = L::agg_operate(right_agg, &self.acc);
233 if (self.f)(&nagg) {
234 return Ordering::Less;
235 }
236 let nagg = L::agg_operate(
237 &L::single_agg(&node.reborrow().into_data().bst_data().key),
238 &nagg,
239 );
240 if (self.f)(&nagg) {
241 Ordering::Equal
242 } else {
243 self.acc = nagg;
244 Ordering::Greater
245 }
246 } else {
247 let nagg = L::agg_operate(
248 &L::single_agg(&node.reborrow().into_data().bst_data().key),
249 &self.acc,
250 );
251 if (self.f)(&nagg) {
252 Ordering::Equal
253 } else {
254 self.acc = nagg;
255 Ordering::Greater
256 }
257 }
258 }crates/competitive/src/data_structure/splay_tree.rs (line 80)
78 fn bottom_up(mut node: BstDataMutRef<'_, Self>) {
79 let left = node
80 .reborrow()
81 .left()
82 .descend()
83 .map(|node| node.into_data().size)
84 .unwrap_or_default();
85 let right = node
86 .reborrow()
87 .right()
88 .descend()
89 .map(|node| node.into_data().size)
90 .unwrap_or_default();
91 node.data_mut().size = left + right + 1;
92 }
93
94 #[inline]
95 fn merge(
96 left: Option<SplayTreeRoot<K, V>>,
97 right: Option<SplayTreeRoot<K, V>>,
98 ) -> Option<SplayTreeRoot<K, V>> {
99 splay_operations::merge(left, right)
100 }
101
102 #[inline]
103 fn split<Seeker>(
104 node: Option<SplayTreeRoot<K, V>>,
105 seeker: Seeker,
106 equal_side: EqualSide,
107 ) -> (Option<SplayTreeRoot<K, V>>, Option<SplayTreeRoot<K, V>>)
108 where
109 Seeker: BstSeeker<Spec = Self>,
110 {
111 splay_operations::split(node, seeker, equal_side)
112 }
113}
114
115pub struct SplayTree<K, V, A = MemoryPool<SplayTreeNode<K, V>>>
116where
117 A: Allocator<SplayTreeNode<K, V>>,
118{
119 root: Option<SplayTreeRoot<K, V>>,
120 length: usize,
121 allocator: ManuallyDrop<A>,
122}
123
124impl<K, V, A> Debug for SplayTree<K, V, A>
125where
126 K: Debug,
127 V: Debug,
128 A: Allocator<SplayTreeNode<K, V>>,
129{
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 f.debug_struct("SplayTree")
132 .field("length", &self.length)
133 .finish_non_exhaustive()
134 }
135}
136
137impl<K, V, A> Default for SplayTree<K, V, A>
138where
139 A: Allocator<SplayTreeNode<K, V>> + Default,
140{
141 fn default() -> Self {
142 Self {
143 root: None,
144 length: 0,
145 allocator: ManuallyDrop::new(A::default()),
146 }
147 }
148}
149
150impl<K, V, A> Drop for SplayTree<K, V, A>
151where
152 A: Allocator<SplayTreeNode<K, V>>,
153{
154 fn drop(&mut self) {
155 unsafe {
156 if let Some(root) = self.root.take() {
157 root.into_dying().drop_all(self.allocator.deref_mut());
158 }
159 ManuallyDrop::drop(&mut self.allocator);
160 }
161 }
162}
163
164impl<K, V> SplayTree<K, V> {
165 pub fn new() -> Self {
166 Self::default()
167 }
168
169 pub fn with_capacity(capacity: usize) -> Self {
170 Self {
171 root: None,
172 length: 0,
173 allocator: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
174 }
175 }
176}
177
178impl<K, V, A> SplayTree<K, V, A>
179where
180 A: Allocator<SplayTreeNode<K, V>>,
181{
182 #[inline]
183 fn splay<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
184 where
185 Seeker: BstSeeker<Spec = SplayTreeSpec<K, V>>,
186 {
187 let (ordering, root) = splay_operations::splay(self.root.take()?, seeker);
188 self.root = Some(root);
189 Some(ordering)
190 }
191
192 fn splay_by_key<Q>(&mut self, key: &Q) -> Option<Ordering>
193 where
194 K: Borrow<Q>,
195 Q: Ord + ?Sized,
196 {
197 self.splay(SeekByKey::new(key))
198 }
199
200 fn splay_by_size(&mut self, index: usize) -> Option<Ordering> {
201 self.splay(SeekBySize::new(index))
202 }
203
204 pub fn get<Q>(&mut self, key: &Q) -> Option<&V>
205 where
206 K: Borrow<Q>,
207 Q: Ord + ?Sized,
208 {
209 self.get_key_value(key).map(|(_, value)| value)
210 }
211
212 pub fn get_key_value<Q>(&mut self, key: &Q) -> Option<(&K, &V)>
213 where
214 K: Borrow<Q>,
215 Q: Ord + ?Sized,
216 {
217 matches!(self.splay_by_key(key)?, Ordering::Equal).then(|| {
218 let data = self.root.as_ref().unwrap().reborrow().into_data();
219 (&data.key, &data.value)
220 })
221 }
222
223 pub fn get_key_value_at(&mut self, index: usize) -> Option<(&K, &V)> {
224 if index >= self.length {
225 return None;
226 }
227 self.splay_by_size(index);
228 let data = self.root.as_ref()?.reborrow().into_data();
229 Some((&data.key, &data.value))
230 }crates/competitive/src/data_structure/implicit_splay_tree.rs (line 88)
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 }crates/competitive/src/data_structure/implicit_treap.rs (line 89)
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 }crates/competitive/src/data_structure/binary_search_tree/data.rs (line 44)
40 pub fn bottom_up<Spec>(mut node: BstDataMutRef<'_, Spec>)
41 where
42 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAgg, Value = Self>>,
43 {
44 let mut agg = node.reborrow().into_data().bst_data().agg.clone();
45 if let Ok(left) = node.reborrow().left().descend() {
46 agg = M::operate(&left.into_data().bst_data().agg, &agg);
47 }
48 if let Ok(right) = node.reborrow().right().descend() {
49 agg = M::operate(&agg, &right.into_data().bst_data().agg);
50 }
51 node.data_mut().bst_data_mut().agg = agg;
52 }
53}
54
55pub struct MonoidActElement<M>
56where
57 M: MonoidAct,
58{
59 pub key: M::Key,
60 pub act: M::Act,
61}
62
63impl<M> Debug for MonoidActElement<M>
64where
65 M: MonoidAct<Key: Debug, Act: Debug>,
66{
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.debug_struct("MonoidActElement")
69 .field("key", &self.key)
70 .field("act", &self.act)
71 .finish()
72 }
73}
74
75impl<M> MonoidActElement<M>
76where
77 M: MonoidAct,
78{
79 pub fn from_key(key: M::Key) -> Self {
80 Self {
81 key,
82 act: M::unit(),
83 }
84 }
85
86 pub fn update_act<Spec>(mut node: BstDataMutRef<'_, Spec>, act: &M::Act)
87 where
88 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAct, Value = Self>>,
89 {
90 M::operate_assign(&mut node.data_mut().bst_data_mut().act, act);
91 M::act_assign(&mut node.data_mut().bst_data_mut().key, act);
92 }
93
94 pub fn top_down<Spec>(mut node: BstDataMutRef<'_, Spec>)
95 where
96 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAct, Value = Self>>,
97 {
98 let act = replace(&mut node.data_mut().bst_data_mut().act, M::unit());
99 if let Ok(left) = node.reborrow_datamut().left().descend() {
100 Self::update_act(left, &act);
101 }
102 if let Ok(right) = node.reborrow_datamut().right().descend() {
103 Self::update_act(right, &act);
104 }
105 }
106}
107
108pub struct LazyMapElement<L>
109where
110 L: LazyMapMonoid,
111{
112 pub key: L::Key,
113 pub agg: L::Agg,
114 pub act: L::Act,
115}
116
117impl<L> Debug for LazyMapElement<L>
118where
119 L: LazyMapMonoid<Key: Debug, Agg: Debug, Act: Debug>,
120{
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.debug_struct("LazyMapElement")
123 .field("key", &self.key)
124 .field("agg", &self.agg)
125 .field("act", &self.act)
126 .finish()
127 }
128}
129
130impl<L> LazyMapElement<L>
131where
132 L: LazyMapMonoid,
133{
134 pub fn from_key(key: L::Key) -> Self {
135 let agg = L::single_agg(&key);
136 Self {
137 key,
138 agg,
139 act: L::act_unit(),
140 }
141 }
142
143 pub fn update_act<Spec>(mut node: BstDataMutRef<'_, Spec>, act: &L::Act)
144 where
145 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
146 {
147 if L::is_act_unit(act) {
148 return;
149 }
150 L::act_operate_assign(&mut node.data_mut().bst_data_mut().act, act);
151 node.data_mut().bst_data_mut().key =
152 L::act_key(&node.reborrow().into_data().bst_data().key, act);
153 if let Some(nxlazy) = L::act_agg(&node.reborrow().into_data().bst_data().agg, act) {
154 node.data_mut().bst_data_mut().agg = nxlazy;
155 } else {
156 Self::top_down(node.reborrow_datamut());
157 Self::bottom_up(node.reborrow_datamut());
158 }
159 }
160
161 pub fn top_down<Spec>(mut node: BstDataMutRef<'_, Spec>)
162 where
163 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
164 {
165 if L::is_act_unit(&node.reborrow().into_data().bst_data().act) {
166 return;
167 }
168 let act = replace(&mut node.data_mut().bst_data_mut().act, L::act_unit());
169 if let Ok(left) = node.reborrow_datamut().left().descend() {
170 Self::update_act(left, &act);
171 }
172 if let Ok(right) = node.reborrow_datamut().right().descend() {
173 Self::update_act(right, &act);
174 }
175 }
176
177 pub fn bottom_up<Spec>(mut node: BstDataMutRef<'_, Spec>)
178 where
179 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
180 {
181 let mut agg = L::single_agg(&node.reborrow().into_data().bst_data().key);
182 if let Ok(left) = node.reborrow().left().descend() {
183 agg = L::agg_operate(&left.into_data().bst_data().agg, &agg);
184 }
185 if let Ok(right) = node.reborrow().right().descend() {
186 agg = L::agg_operate(&agg, &right.into_data().bst_data().agg);
187 }
188 node.data_mut().bst_data_mut().agg = agg;
189 }Sourcepub fn left(self) -> BstEdgeHandle<Self, Left>
pub fn left(self) -> BstEdgeHandle<Self, Left>
Examples found in repository?
crates/competitive/src/data_structure/binary_search_tree/seeker.rs (line 29)
28 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
29 if node.reborrow().left().descend().is_ok() {
30 Ordering::Greater
31 } else {
32 Ordering::Equal
33 }
34 }
35}
36
37pub struct SeekRight<Spec> {
38 _marker: PhantomData<fn() -> Spec>,
39}
40
41impl<S> Default for SeekRight<S> {
42 fn default() -> Self {
43 Self {
44 _marker: PhantomData,
45 }
46 }
47}
48
49impl<Spec> BstSeeker for SeekRight<Spec>
50where
51 Spec: BstSpec,
52{
53 type Spec = Spec;
54 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
55 if node.reborrow().right().descend().is_ok() {
56 Ordering::Less
57 } else {
58 Ordering::Equal
59 }
60 }
61}
62
63pub struct SeekByKey<'a, Spec, K, Q>
64where
65 Q: ?Sized,
66{
67 key: &'a Q,
68 _marker: PhantomData<fn() -> (Spec, K)>,
69}
70
71impl<'a, Spec, K, Q> SeekByKey<'a, Spec, K, Q>
72where
73 Q: ?Sized,
74{
75 pub fn new(key: &'a Q) -> Self {
76 Self {
77 key,
78 _marker: PhantomData,
79 }
80 }
81}
82
83impl<Spec, K, Q> BstSeeker for SeekByKey<'_, Spec, K, Q>
84where
85 Spec: BstSpec<Data: BstDataAccess<data::marker::Key, Value = K>>,
86 K: Borrow<Q>,
87 Q: Ord + ?Sized,
88{
89 type Spec = Spec;
90
91 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
92 node.reborrow()
93 .into_data()
94 .bst_data()
95 .borrow()
96 .cmp(self.key)
97 }
98}
99
100pub struct SeekBySize<Spec> {
101 index: usize,
102 _marker: PhantomData<fn() -> Spec>,
103}
104
105impl<Spec> SeekBySize<Spec> {
106 pub fn new(index: usize) -> Self {
107 Self {
108 index,
109 _marker: PhantomData,
110 }
111 }
112}
113
114impl<Spec> BstSeeker for SeekBySize<Spec>
115where
116 Spec: BstSpec<Data: BstDataAccess<data::marker::Size, Value = usize>>,
117{
118 type Spec = Spec;
119
120 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
121 let lsize = node
122 .reborrow()
123 .left()
124 .descend()
125 .map(|l| *l.into_data().bst_data())
126 .unwrap_or_default();
127 let ord = lsize.cmp(&self.index);
128 if matches!(ord, Ordering::Less) {
129 self.index -= lsize + 1;
130 }
131 ord
132 }
133}
134
135pub struct SeekByAccCond<Spec, L, F>
136where
137 L: LazyMapMonoid,
138{
139 acc: L::Agg,
140 f: F,
141 _marker: PhantomData<fn() -> (Spec, L)>,
142}
143
144impl<Spec, L, F> SeekByAccCond<Spec, L, F>
145where
146 L: LazyMapMonoid,
147 F: FnMut(&L::Agg) -> bool,
148{
149 pub fn new(f: F) -> Self {
150 Self {
151 acc: L::agg_unit(),
152 f,
153 _marker: PhantomData,
154 }
155 }
156}
157
158impl<Spec, L, F> BstSeeker for SeekByAccCond<Spec, L, F>
159where
160 Spec: BstSpec<Data: BstDataAccess<data::marker::LazyMap, Value = LazyMapElement<L>>>,
161 L: LazyMapMonoid,
162 F: FnMut(&L::Agg) -> bool,
163{
164 type Spec = Spec;
165
166 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
167 if let Ok(left) = node.reborrow().left().descend() {
168 let left_agg = &left.into_data().bst_data().agg;
169 let nagg = L::agg_operate(&self.acc, left_agg);
170 if (self.f)(&nagg) {
171 return Ordering::Greater;
172 }
173 let nagg = L::agg_operate(
174 &nagg,
175 &L::single_agg(&node.reborrow().into_data().bst_data().key),
176 );
177 if (self.f)(&nagg) {
178 Ordering::Equal
179 } else {
180 self.acc = nagg;
181 Ordering::Less
182 }
183 } else {
184 let nagg = L::agg_operate(
185 &self.acc,
186 &L::single_agg(&node.reborrow().into_data().bst_data().key),
187 );
188 if (self.f)(&nagg) {
189 Ordering::Equal
190 } else {
191 self.acc = nagg;
192 Ordering::Less
193 }
194 }
195 }More examples
crates/competitive/src/data_structure/splay_tree.rs (line 81)
78 fn bottom_up(mut node: BstDataMutRef<'_, Self>) {
79 let left = node
80 .reborrow()
81 .left()
82 .descend()
83 .map(|node| node.into_data().size)
84 .unwrap_or_default();
85 let right = node
86 .reborrow()
87 .right()
88 .descend()
89 .map(|node| node.into_data().size)
90 .unwrap_or_default();
91 node.data_mut().size = left + right + 1;
92 }crates/competitive/src/data_structure/binary_search_tree/data.rs (line 45)
40 pub fn bottom_up<Spec>(mut node: BstDataMutRef<'_, Spec>)
41 where
42 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAgg, Value = Self>>,
43 {
44 let mut agg = node.reborrow().into_data().bst_data().agg.clone();
45 if let Ok(left) = node.reborrow().left().descend() {
46 agg = M::operate(&left.into_data().bst_data().agg, &agg);
47 }
48 if let Ok(right) = node.reborrow().right().descend() {
49 agg = M::operate(&agg, &right.into_data().bst_data().agg);
50 }
51 node.data_mut().bst_data_mut().agg = agg;
52 }
53}
54
55pub struct MonoidActElement<M>
56where
57 M: MonoidAct,
58{
59 pub key: M::Key,
60 pub act: M::Act,
61}
62
63impl<M> Debug for MonoidActElement<M>
64where
65 M: MonoidAct<Key: Debug, Act: Debug>,
66{
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.debug_struct("MonoidActElement")
69 .field("key", &self.key)
70 .field("act", &self.act)
71 .finish()
72 }
73}
74
75impl<M> MonoidActElement<M>
76where
77 M: MonoidAct,
78{
79 pub fn from_key(key: M::Key) -> Self {
80 Self {
81 key,
82 act: M::unit(),
83 }
84 }
85
86 pub fn update_act<Spec>(mut node: BstDataMutRef<'_, Spec>, act: &M::Act)
87 where
88 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAct, Value = Self>>,
89 {
90 M::operate_assign(&mut node.data_mut().bst_data_mut().act, act);
91 M::act_assign(&mut node.data_mut().bst_data_mut().key, act);
92 }
93
94 pub fn top_down<Spec>(mut node: BstDataMutRef<'_, Spec>)
95 where
96 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAct, Value = Self>>,
97 {
98 let act = replace(&mut node.data_mut().bst_data_mut().act, M::unit());
99 if let Ok(left) = node.reborrow_datamut().left().descend() {
100 Self::update_act(left, &act);
101 }
102 if let Ok(right) = node.reborrow_datamut().right().descend() {
103 Self::update_act(right, &act);
104 }
105 }
106}
107
108pub struct LazyMapElement<L>
109where
110 L: LazyMapMonoid,
111{
112 pub key: L::Key,
113 pub agg: L::Agg,
114 pub act: L::Act,
115}
116
117impl<L> Debug for LazyMapElement<L>
118where
119 L: LazyMapMonoid<Key: Debug, Agg: Debug, Act: Debug>,
120{
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.debug_struct("LazyMapElement")
123 .field("key", &self.key)
124 .field("agg", &self.agg)
125 .field("act", &self.act)
126 .finish()
127 }
128}
129
130impl<L> LazyMapElement<L>
131where
132 L: LazyMapMonoid,
133{
134 pub fn from_key(key: L::Key) -> Self {
135 let agg = L::single_agg(&key);
136 Self {
137 key,
138 agg,
139 act: L::act_unit(),
140 }
141 }
142
143 pub fn update_act<Spec>(mut node: BstDataMutRef<'_, Spec>, act: &L::Act)
144 where
145 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
146 {
147 if L::is_act_unit(act) {
148 return;
149 }
150 L::act_operate_assign(&mut node.data_mut().bst_data_mut().act, act);
151 node.data_mut().bst_data_mut().key =
152 L::act_key(&node.reborrow().into_data().bst_data().key, act);
153 if let Some(nxlazy) = L::act_agg(&node.reborrow().into_data().bst_data().agg, act) {
154 node.data_mut().bst_data_mut().agg = nxlazy;
155 } else {
156 Self::top_down(node.reborrow_datamut());
157 Self::bottom_up(node.reborrow_datamut());
158 }
159 }
160
161 pub fn top_down<Spec>(mut node: BstDataMutRef<'_, Spec>)
162 where
163 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
164 {
165 if L::is_act_unit(&node.reborrow().into_data().bst_data().act) {
166 return;
167 }
168 let act = replace(&mut node.data_mut().bst_data_mut().act, L::act_unit());
169 if let Ok(left) = node.reborrow_datamut().left().descend() {
170 Self::update_act(left, &act);
171 }
172 if let Ok(right) = node.reborrow_datamut().right().descend() {
173 Self::update_act(right, &act);
174 }
175 }
176
177 pub fn bottom_up<Spec>(mut node: BstDataMutRef<'_, Spec>)
178 where
179 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
180 {
181 let mut agg = L::single_agg(&node.reborrow().into_data().bst_data().key);
182 if let Ok(left) = node.reborrow().left().descend() {
183 agg = L::agg_operate(&left.into_data().bst_data().agg, &agg);
184 }
185 if let Ok(right) = node.reborrow().right().descend() {
186 agg = L::agg_operate(&agg, &right.into_data().bst_data().agg);
187 }
188 node.data_mut().bst_data_mut().agg = agg;
189 }crates/competitive/src/data_structure/binary_search_tree/node.rs (line 148)
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 }
156
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 }
237}
238
239pub struct BstNodeRef<BorrowType, Spec>
240where
241 Spec: BstSpec,
242{
243 pub node: NonNull<BstNode<Spec::Data, Spec::Parent>>,
244 _marker: PhantomData<BorrowType>,
245}
246
247impl<'a, Spec> Copy for BstNodeRef<marker::Immut<'a>, Spec> where Spec: BstSpec<Data: 'a> {}
248impl<'a, Spec> Clone for BstNodeRef<marker::Immut<'a>, Spec>
249where
250 Spec: BstSpec<Data: 'a>,
251{
252 fn clone(&self) -> Self {
253 *self
254 }
255}
256
257impl<BorrowType, Spec> BstNodeRef<BorrowType, Spec>
258where
259 Spec: BstSpec,
260 BorrowType: marker::BorrowType,
261{
262 pub unsafe fn new_unchecked(node: NonNull<BstNode<Spec::Data, Spec::Parent>>) -> Self {
263 Self {
264 node,
265 _marker: PhantomData,
266 }
267 }
268 pub fn reborrow(&self) -> BstNodeRef<marker::Immut<'_>, Spec> {
269 BstNodeRef {
270 node: self.node,
271 _marker: PhantomData,
272 }
273 }
274 pub fn left(self) -> BstEdgeHandle<Self, marker::Left> {
275 BstEdgeHandle {
276 node: self,
277 _marker: PhantomData,
278 }
279 }
280 pub fn right(self) -> BstEdgeHandle<Self, marker::Right> {
281 BstEdgeHandle {
282 node: self,
283 _marker: PhantomData,
284 }
285 }
286}
287
288impl<BorrowType, Spec, Data> BstNodeRef<BorrowType, Spec>
289where
290 Spec: BstSpec<Data = Data, Parent = WithParent<Data>>,
291 BorrowType: marker::BorrowType,
292{
293 pub fn ascend(self) -> Result<BstNodeRef<BorrowType, Spec>, Self> {
294 const {
295 assert!(BorrowType::TRAVERSAL_PERMIT);
296 };
297 let parent = unsafe { self.node.as_ref().parent.parent };
298 parent
299 .map(|node| BstNodeRef {
300 node,
301 _marker: PhantomData,
302 })
303 .ok_or(self)
304 }
305 pub fn root_path(self) -> (Self, Vec<bool>) {
306 let mut node = self;
307 let mut nn = node.node;
308 let mut stack = vec![];
309 let root = loop {
310 match node.ascend() {
311 Ok(parent) => {
312 node = parent;
313 stack.push(
314 node.reborrow()
315 .left()
316 .descend()
317 .is_ok_and(|node| node.node == nn),
318 );
319 nn = node.node;
320 }
321 Err(node) => {
322 break node;
323 }
324 }
325 };
326 (root, stack)
327 }
328}
329
330impl<Spec> BstNodeRef<marker::Owned, Spec>
331where
332 Spec: BstSpec,
333{
334 pub fn new(node: NonNull<BstNode<Spec::Data, Spec::Parent>>) -> Self {
335 Self {
336 node,
337 _marker: PhantomData,
338 }
339 }
340 pub fn from_data<A>(data: Spec::Data, allocator: &mut A) -> Self
341 where
342 A: Allocator<BstNode<Spec::Data, Spec::Parent>>,
343 {
344 Self::new(allocator.allocate(BstNode::new(data)))
345 }
346 pub fn borrow_mut(&mut self) -> BstNodeRef<marker::Mut<'_>, Spec> {
347 BstNodeRef {
348 node: self.node,
349 _marker: PhantomData,
350 }
351 }
352 pub fn borrow_datamut(&mut self) -> BstNodeRef<marker::DataMut<'_>, Spec> {
353 BstNodeRef {
354 node: self.node,
355 _marker: PhantomData,
356 }
357 }
358 pub fn into_dying(self) -> BstNodeRef<marker::Dying, Spec> {
359 BstNodeRef {
360 node: self.node,
361 _marker: PhantomData,
362 }
363 }
364}
365
366impl<'a, Spec> BstNodeRef<marker::Immut<'a>, Spec>
367where
368 Spec: BstSpec<Parent: 'a, Data: 'a>,
369{
370 pub fn into_data(self) -> &'a Spec::Data {
371 unsafe { &self.node.as_ref().data }
372 }
373
374 pub fn traverse<F>(self, f: &mut F)
375 where
376 F: FnMut(Self),
377 {
378 if let Ok(left) = self.left().descend() {
379 left.traverse(f);
380 }
381 f(self);
382 if let Ok(right) = self.right().descend() {
383 right.traverse(f);
384 }
385 }
386
387 pub fn leftmost(self) -> Self {
388 let mut node = self;
389 while let Ok(left) = node.left().descend() {
390 node = left;
391 }
392 node
393 }
394
395 pub fn rightmost(self) -> Self {
396 let mut node = self;
397 while let Ok(right) = node.right().descend() {
398 node = right;
399 }
400 node
401 }
402}
403
404impl<'a, Spec> BstNodeRef<marker::DataMut<'a>, Spec>
405where
406 Spec: BstSpec,
407{
408 pub fn reborrow_datamut(&mut self) -> BstNodeRef<marker::DataMut<'_>, Spec> {
409 BstNodeRef {
410 node: self.node,
411 _marker: PhantomData,
412 }
413 }
414 pub fn data_mut(&mut self) -> &mut Spec::Data {
415 unsafe { &mut self.node.as_mut().data }
416 }
417
418 pub fn swap_children(&mut self) {
419 unsafe { self.node.as_mut().child.swap(0, 1) };
420 }
421}
422
423impl<'a, Spec> BstNodeRef<marker::DataMut<'a>, Spec>
424where
425 Spec: BstSpec<Parent: 'a, Data: 'a>,
426{
427 pub fn into_data_mut(mut self) -> &'a mut Spec::Data {
428 unsafe { &mut self.node.as_mut().data }
429 }
430}
431
432impl<'a, Spec> BstNodeRef<marker::Mut<'a>, Spec>
433where
434 Spec: BstSpec,
435{
436 pub fn reborrow_datamut(&mut self) -> BstNodeRef<marker::DataMut<'_>, Spec> {
437 BstNodeRef {
438 node: self.node,
439 _marker: PhantomData,
440 }
441 }
442
443 pub fn left_mut(&mut self) -> BstEdgeHandle<BstNodeRef<marker::Mut<'_>, Spec>, marker::Left> {
444 BstEdgeHandle {
445 node: BstNodeRef {
446 node: self.node,
447 _marker: PhantomData,
448 },
449 _marker: PhantomData,
450 }
451 }
452
453 pub fn right_mut(&mut self) -> BstEdgeHandle<BstNodeRef<marker::Mut<'_>, Spec>, marker::Right> {
454 BstEdgeHandle {
455 node: BstNodeRef {
456 node: self.node,
457 _marker: PhantomData,
458 },
459 _marker: PhantomData,
460 }
461 }
462}
463
464impl<'a, Spec> BstNodeRef<marker::Mut<'a>, Spec>
465where
466 Spec: BstSpec<Data: 'a>,
467{
468 pub fn dormant(self) -> BstNodeRef<marker::DormantMut, Spec> {
469 BstNodeRef {
470 node: self.node,
471 _marker: PhantomData,
472 }
473 }
474}
475
476impl<Spec> BstNodeRef<marker::DormantMut, Spec>
477where
478 Spec: BstSpec,
479{
480 pub unsafe fn awaken<'a>(self) -> BstNodeRef<marker::Mut<'a>, Spec> {
481 BstNodeRef {
482 node: self.node,
483 _marker: PhantomData,
484 }
485 }
486}
487
488impl<Spec> BstNodeRef<marker::Dying, Spec>
489where
490 Spec: BstSpec,
491{
492 pub unsafe fn into_data<A>(self, allocator: &mut A) -> Spec::Data
493 where
494 A: Allocator<BstNode<Spec::Data, Spec::Parent>>,
495 {
496 debug_assert!(self.reborrow().left().descend().is_err());
497 debug_assert!(self.reborrow().right().descend().is_err());
498 allocator.deallocate(self.node).data
499 }crates/competitive/src/data_structure/implicit_splay_tree.rs (line 115)
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 }crates/competitive/src/data_structure/implicit_treap.rs (line 116)
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 }Additional examples can be found in:
Sourcepub fn right(self) -> BstEdgeHandle<Self, Right>
pub fn right(self) -> BstEdgeHandle<Self, Right>
Examples found in repository?
crates/competitive/src/data_structure/binary_search_tree/seeker.rs (line 55)
54 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
55 if node.reborrow().right().descend().is_ok() {
56 Ordering::Less
57 } else {
58 Ordering::Equal
59 }
60 }
61}
62
63pub struct SeekByKey<'a, Spec, K, Q>
64where
65 Q: ?Sized,
66{
67 key: &'a Q,
68 _marker: PhantomData<fn() -> (Spec, K)>,
69}
70
71impl<'a, Spec, K, Q> SeekByKey<'a, Spec, K, Q>
72where
73 Q: ?Sized,
74{
75 pub fn new(key: &'a Q) -> Self {
76 Self {
77 key,
78 _marker: PhantomData,
79 }
80 }
81}
82
83impl<Spec, K, Q> BstSeeker for SeekByKey<'_, Spec, K, Q>
84where
85 Spec: BstSpec<Data: BstDataAccess<data::marker::Key, Value = K>>,
86 K: Borrow<Q>,
87 Q: Ord + ?Sized,
88{
89 type Spec = Spec;
90
91 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
92 node.reborrow()
93 .into_data()
94 .bst_data()
95 .borrow()
96 .cmp(self.key)
97 }
98}
99
100pub struct SeekBySize<Spec> {
101 index: usize,
102 _marker: PhantomData<fn() -> Spec>,
103}
104
105impl<Spec> SeekBySize<Spec> {
106 pub fn new(index: usize) -> Self {
107 Self {
108 index,
109 _marker: PhantomData,
110 }
111 }
112}
113
114impl<Spec> BstSeeker for SeekBySize<Spec>
115where
116 Spec: BstSpec<Data: BstDataAccess<data::marker::Size, Value = usize>>,
117{
118 type Spec = Spec;
119
120 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
121 let lsize = node
122 .reborrow()
123 .left()
124 .descend()
125 .map(|l| *l.into_data().bst_data())
126 .unwrap_or_default();
127 let ord = lsize.cmp(&self.index);
128 if matches!(ord, Ordering::Less) {
129 self.index -= lsize + 1;
130 }
131 ord
132 }
133}
134
135pub struct SeekByAccCond<Spec, L, F>
136where
137 L: LazyMapMonoid,
138{
139 acc: L::Agg,
140 f: F,
141 _marker: PhantomData<fn() -> (Spec, L)>,
142}
143
144impl<Spec, L, F> SeekByAccCond<Spec, L, F>
145where
146 L: LazyMapMonoid,
147 F: FnMut(&L::Agg) -> bool,
148{
149 pub fn new(f: F) -> Self {
150 Self {
151 acc: L::agg_unit(),
152 f,
153 _marker: PhantomData,
154 }
155 }
156}
157
158impl<Spec, L, F> BstSeeker for SeekByAccCond<Spec, L, F>
159where
160 Spec: BstSpec<Data: BstDataAccess<data::marker::LazyMap, Value = LazyMapElement<L>>>,
161 L: LazyMapMonoid,
162 F: FnMut(&L::Agg) -> bool,
163{
164 type Spec = Spec;
165
166 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
167 if let Ok(left) = node.reborrow().left().descend() {
168 let left_agg = &left.into_data().bst_data().agg;
169 let nagg = L::agg_operate(&self.acc, left_agg);
170 if (self.f)(&nagg) {
171 return Ordering::Greater;
172 }
173 let nagg = L::agg_operate(
174 &nagg,
175 &L::single_agg(&node.reborrow().into_data().bst_data().key),
176 );
177 if (self.f)(&nagg) {
178 Ordering::Equal
179 } else {
180 self.acc = nagg;
181 Ordering::Less
182 }
183 } else {
184 let nagg = L::agg_operate(
185 &self.acc,
186 &L::single_agg(&node.reborrow().into_data().bst_data().key),
187 );
188 if (self.f)(&nagg) {
189 Ordering::Equal
190 } else {
191 self.acc = nagg;
192 Ordering::Less
193 }
194 }
195 }
196}
197
198pub struct SeekByRaccCond<Spec, L, F>
199where
200 L: LazyMapMonoid,
201{
202 acc: L::Agg,
203 f: F,
204 _marker: PhantomData<fn() -> (Spec, L)>,
205}
206
207impl<Spec, L, F> SeekByRaccCond<Spec, L, F>
208where
209 L: LazyMapMonoid,
210 F: FnMut(&L::Agg) -> bool,
211{
212 pub fn new(f: F) -> Self {
213 Self {
214 acc: L::agg_unit(),
215 f,
216 _marker: PhantomData,
217 }
218 }
219}
220
221impl<Spec, L, F> BstSeeker for SeekByRaccCond<Spec, L, F>
222where
223 Spec: BstSpec<Data: BstDataAccess<data::marker::LazyMap, Value = LazyMapElement<L>>>,
224 L: LazyMapMonoid,
225 F: FnMut(&L::Agg) -> bool,
226{
227 type Spec = Spec;
228
229 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
230 if let Ok(right) = node.reborrow().right().descend() {
231 let right_agg = &right.into_data().bst_data().agg;
232 let nagg = L::agg_operate(right_agg, &self.acc);
233 if (self.f)(&nagg) {
234 return Ordering::Less;
235 }
236 let nagg = L::agg_operate(
237 &L::single_agg(&node.reborrow().into_data().bst_data().key),
238 &nagg,
239 );
240 if (self.f)(&nagg) {
241 Ordering::Equal
242 } else {
243 self.acc = nagg;
244 Ordering::Greater
245 }
246 } else {
247 let nagg = L::agg_operate(
248 &L::single_agg(&node.reborrow().into_data().bst_data().key),
249 &self.acc,
250 );
251 if (self.f)(&nagg) {
252 Ordering::Equal
253 } else {
254 self.acc = nagg;
255 Ordering::Greater
256 }
257 }
258 }More examples
crates/competitive/src/data_structure/splay_tree.rs (line 87)
78 fn bottom_up(mut node: BstDataMutRef<'_, Self>) {
79 let left = node
80 .reborrow()
81 .left()
82 .descend()
83 .map(|node| node.into_data().size)
84 .unwrap_or_default();
85 let right = node
86 .reborrow()
87 .right()
88 .descend()
89 .map(|node| node.into_data().size)
90 .unwrap_or_default();
91 node.data_mut().size = left + right + 1;
92 }crates/competitive/src/data_structure/binary_search_tree/data.rs (line 48)
40 pub fn bottom_up<Spec>(mut node: BstDataMutRef<'_, Spec>)
41 where
42 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAgg, Value = Self>>,
43 {
44 let mut agg = node.reborrow().into_data().bst_data().agg.clone();
45 if let Ok(left) = node.reborrow().left().descend() {
46 agg = M::operate(&left.into_data().bst_data().agg, &agg);
47 }
48 if let Ok(right) = node.reborrow().right().descend() {
49 agg = M::operate(&agg, &right.into_data().bst_data().agg);
50 }
51 node.data_mut().bst_data_mut().agg = agg;
52 }
53}
54
55pub struct MonoidActElement<M>
56where
57 M: MonoidAct,
58{
59 pub key: M::Key,
60 pub act: M::Act,
61}
62
63impl<M> Debug for MonoidActElement<M>
64where
65 M: MonoidAct<Key: Debug, Act: Debug>,
66{
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.debug_struct("MonoidActElement")
69 .field("key", &self.key)
70 .field("act", &self.act)
71 .finish()
72 }
73}
74
75impl<M> MonoidActElement<M>
76where
77 M: MonoidAct,
78{
79 pub fn from_key(key: M::Key) -> Self {
80 Self {
81 key,
82 act: M::unit(),
83 }
84 }
85
86 pub fn update_act<Spec>(mut node: BstDataMutRef<'_, Spec>, act: &M::Act)
87 where
88 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAct, Value = Self>>,
89 {
90 M::operate_assign(&mut node.data_mut().bst_data_mut().act, act);
91 M::act_assign(&mut node.data_mut().bst_data_mut().key, act);
92 }
93
94 pub fn top_down<Spec>(mut node: BstDataMutRef<'_, Spec>)
95 where
96 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAct, Value = Self>>,
97 {
98 let act = replace(&mut node.data_mut().bst_data_mut().act, M::unit());
99 if let Ok(left) = node.reborrow_datamut().left().descend() {
100 Self::update_act(left, &act);
101 }
102 if let Ok(right) = node.reborrow_datamut().right().descend() {
103 Self::update_act(right, &act);
104 }
105 }
106}
107
108pub struct LazyMapElement<L>
109where
110 L: LazyMapMonoid,
111{
112 pub key: L::Key,
113 pub agg: L::Agg,
114 pub act: L::Act,
115}
116
117impl<L> Debug for LazyMapElement<L>
118where
119 L: LazyMapMonoid<Key: Debug, Agg: Debug, Act: Debug>,
120{
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.debug_struct("LazyMapElement")
123 .field("key", &self.key)
124 .field("agg", &self.agg)
125 .field("act", &self.act)
126 .finish()
127 }
128}
129
130impl<L> LazyMapElement<L>
131where
132 L: LazyMapMonoid,
133{
134 pub fn from_key(key: L::Key) -> Self {
135 let agg = L::single_agg(&key);
136 Self {
137 key,
138 agg,
139 act: L::act_unit(),
140 }
141 }
142
143 pub fn update_act<Spec>(mut node: BstDataMutRef<'_, Spec>, act: &L::Act)
144 where
145 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
146 {
147 if L::is_act_unit(act) {
148 return;
149 }
150 L::act_operate_assign(&mut node.data_mut().bst_data_mut().act, act);
151 node.data_mut().bst_data_mut().key =
152 L::act_key(&node.reborrow().into_data().bst_data().key, act);
153 if let Some(nxlazy) = L::act_agg(&node.reborrow().into_data().bst_data().agg, act) {
154 node.data_mut().bst_data_mut().agg = nxlazy;
155 } else {
156 Self::top_down(node.reborrow_datamut());
157 Self::bottom_up(node.reborrow_datamut());
158 }
159 }
160
161 pub fn top_down<Spec>(mut node: BstDataMutRef<'_, Spec>)
162 where
163 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
164 {
165 if L::is_act_unit(&node.reborrow().into_data().bst_data().act) {
166 return;
167 }
168 let act = replace(&mut node.data_mut().bst_data_mut().act, L::act_unit());
169 if let Ok(left) = node.reborrow_datamut().left().descend() {
170 Self::update_act(left, &act);
171 }
172 if let Ok(right) = node.reborrow_datamut().right().descend() {
173 Self::update_act(right, &act);
174 }
175 }
176
177 pub fn bottom_up<Spec>(mut node: BstDataMutRef<'_, Spec>)
178 where
179 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
180 {
181 let mut agg = L::single_agg(&node.reborrow().into_data().bst_data().key);
182 if let Ok(left) = node.reborrow().left().descend() {
183 agg = L::agg_operate(&left.into_data().bst_data().agg, &agg);
184 }
185 if let Ok(right) = node.reborrow().right().descend() {
186 agg = L::agg_operate(&agg, &right.into_data().bst_data().agg);
187 }
188 node.data_mut().bst_data_mut().agg = agg;
189 }crates/competitive/src/data_structure/binary_search_tree/node.rs (line 150)
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 }
156
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 }
237}
238
239pub struct BstNodeRef<BorrowType, Spec>
240where
241 Spec: BstSpec,
242{
243 pub node: NonNull<BstNode<Spec::Data, Spec::Parent>>,
244 _marker: PhantomData<BorrowType>,
245}
246
247impl<'a, Spec> Copy for BstNodeRef<marker::Immut<'a>, Spec> where Spec: BstSpec<Data: 'a> {}
248impl<'a, Spec> Clone for BstNodeRef<marker::Immut<'a>, Spec>
249where
250 Spec: BstSpec<Data: 'a>,
251{
252 fn clone(&self) -> Self {
253 *self
254 }
255}
256
257impl<BorrowType, Spec> BstNodeRef<BorrowType, Spec>
258where
259 Spec: BstSpec,
260 BorrowType: marker::BorrowType,
261{
262 pub unsafe fn new_unchecked(node: NonNull<BstNode<Spec::Data, Spec::Parent>>) -> Self {
263 Self {
264 node,
265 _marker: PhantomData,
266 }
267 }
268 pub fn reborrow(&self) -> BstNodeRef<marker::Immut<'_>, Spec> {
269 BstNodeRef {
270 node: self.node,
271 _marker: PhantomData,
272 }
273 }
274 pub fn left(self) -> BstEdgeHandle<Self, marker::Left> {
275 BstEdgeHandle {
276 node: self,
277 _marker: PhantomData,
278 }
279 }
280 pub fn right(self) -> BstEdgeHandle<Self, marker::Right> {
281 BstEdgeHandle {
282 node: self,
283 _marker: PhantomData,
284 }
285 }
286}
287
288impl<BorrowType, Spec, Data> BstNodeRef<BorrowType, Spec>
289where
290 Spec: BstSpec<Data = Data, Parent = WithParent<Data>>,
291 BorrowType: marker::BorrowType,
292{
293 pub fn ascend(self) -> Result<BstNodeRef<BorrowType, Spec>, Self> {
294 const {
295 assert!(BorrowType::TRAVERSAL_PERMIT);
296 };
297 let parent = unsafe { self.node.as_ref().parent.parent };
298 parent
299 .map(|node| BstNodeRef {
300 node,
301 _marker: PhantomData,
302 })
303 .ok_or(self)
304 }
305 pub fn root_path(self) -> (Self, Vec<bool>) {
306 let mut node = self;
307 let mut nn = node.node;
308 let mut stack = vec![];
309 let root = loop {
310 match node.ascend() {
311 Ok(parent) => {
312 node = parent;
313 stack.push(
314 node.reborrow()
315 .left()
316 .descend()
317 .is_ok_and(|node| node.node == nn),
318 );
319 nn = node.node;
320 }
321 Err(node) => {
322 break node;
323 }
324 }
325 };
326 (root, stack)
327 }
328}
329
330impl<Spec> BstNodeRef<marker::Owned, Spec>
331where
332 Spec: BstSpec,
333{
334 pub fn new(node: NonNull<BstNode<Spec::Data, Spec::Parent>>) -> Self {
335 Self {
336 node,
337 _marker: PhantomData,
338 }
339 }
340 pub fn from_data<A>(data: Spec::Data, allocator: &mut A) -> Self
341 where
342 A: Allocator<BstNode<Spec::Data, Spec::Parent>>,
343 {
344 Self::new(allocator.allocate(BstNode::new(data)))
345 }
346 pub fn borrow_mut(&mut self) -> BstNodeRef<marker::Mut<'_>, Spec> {
347 BstNodeRef {
348 node: self.node,
349 _marker: PhantomData,
350 }
351 }
352 pub fn borrow_datamut(&mut self) -> BstNodeRef<marker::DataMut<'_>, Spec> {
353 BstNodeRef {
354 node: self.node,
355 _marker: PhantomData,
356 }
357 }
358 pub fn into_dying(self) -> BstNodeRef<marker::Dying, Spec> {
359 BstNodeRef {
360 node: self.node,
361 _marker: PhantomData,
362 }
363 }
364}
365
366impl<'a, Spec> BstNodeRef<marker::Immut<'a>, Spec>
367where
368 Spec: BstSpec<Parent: 'a, Data: 'a>,
369{
370 pub fn into_data(self) -> &'a Spec::Data {
371 unsafe { &self.node.as_ref().data }
372 }
373
374 pub fn traverse<F>(self, f: &mut F)
375 where
376 F: FnMut(Self),
377 {
378 if let Ok(left) = self.left().descend() {
379 left.traverse(f);
380 }
381 f(self);
382 if let Ok(right) = self.right().descend() {
383 right.traverse(f);
384 }
385 }
386
387 pub fn leftmost(self) -> Self {
388 let mut node = self;
389 while let Ok(left) = node.left().descend() {
390 node = left;
391 }
392 node
393 }
394
395 pub fn rightmost(self) -> Self {
396 let mut node = self;
397 while let Ok(right) = node.right().descend() {
398 node = right;
399 }
400 node
401 }
402}
403
404impl<'a, Spec> BstNodeRef<marker::DataMut<'a>, Spec>
405where
406 Spec: BstSpec,
407{
408 pub fn reborrow_datamut(&mut self) -> BstNodeRef<marker::DataMut<'_>, Spec> {
409 BstNodeRef {
410 node: self.node,
411 _marker: PhantomData,
412 }
413 }
414 pub fn data_mut(&mut self) -> &mut Spec::Data {
415 unsafe { &mut self.node.as_mut().data }
416 }
417
418 pub fn swap_children(&mut self) {
419 unsafe { self.node.as_mut().child.swap(0, 1) };
420 }
421}
422
423impl<'a, Spec> BstNodeRef<marker::DataMut<'a>, Spec>
424where
425 Spec: BstSpec<Parent: 'a, Data: 'a>,
426{
427 pub fn into_data_mut(mut self) -> &'a mut Spec::Data {
428 unsafe { &mut self.node.as_mut().data }
429 }
430}
431
432impl<'a, Spec> BstNodeRef<marker::Mut<'a>, Spec>
433where
434 Spec: BstSpec,
435{
436 pub fn reborrow_datamut(&mut self) -> BstNodeRef<marker::DataMut<'_>, Spec> {
437 BstNodeRef {
438 node: self.node,
439 _marker: PhantomData,
440 }
441 }
442
443 pub fn left_mut(&mut self) -> BstEdgeHandle<BstNodeRef<marker::Mut<'_>, Spec>, marker::Left> {
444 BstEdgeHandle {
445 node: BstNodeRef {
446 node: self.node,
447 _marker: PhantomData,
448 },
449 _marker: PhantomData,
450 }
451 }
452
453 pub fn right_mut(&mut self) -> BstEdgeHandle<BstNodeRef<marker::Mut<'_>, Spec>, marker::Right> {
454 BstEdgeHandle {
455 node: BstNodeRef {
456 node: self.node,
457 _marker: PhantomData,
458 },
459 _marker: PhantomData,
460 }
461 }
462}
463
464impl<'a, Spec> BstNodeRef<marker::Mut<'a>, Spec>
465where
466 Spec: BstSpec<Data: 'a>,
467{
468 pub fn dormant(self) -> BstNodeRef<marker::DormantMut, Spec> {
469 BstNodeRef {
470 node: self.node,
471 _marker: PhantomData,
472 }
473 }
474}
475
476impl<Spec> BstNodeRef<marker::DormantMut, Spec>
477where
478 Spec: BstSpec,
479{
480 pub unsafe fn awaken<'a>(self) -> BstNodeRef<marker::Mut<'a>, Spec> {
481 BstNodeRef {
482 node: self.node,
483 _marker: PhantomData,
484 }
485 }
486}
487
488impl<Spec> BstNodeRef<marker::Dying, Spec>
489where
490 Spec: BstSpec,
491{
492 pub unsafe fn into_data<A>(self, allocator: &mut A) -> Spec::Data
493 where
494 A: Allocator<BstNode<Spec::Data, Spec::Parent>>,
495 {
496 debug_assert!(self.reborrow().left().descend().is_err());
497 debug_assert!(self.reborrow().right().descend().is_err());
498 allocator.deallocate(self.node).data
499 }crates/competitive/src/data_structure/implicit_splay_tree.rs (line 118)
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 }crates/competitive/src/data_structure/implicit_treap.rs (line 119)
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 }Additional examples can be found in:
Source§impl<BorrowType, Spec, Data> BstNodeRef<BorrowType, Spec>
impl<BorrowType, Spec, Data> BstNodeRef<BorrowType, Spec>
Sourcepub fn ascend(self) -> Result<BstNodeRef<BorrowType, Spec>, Self>
pub fn ascend(self) -> Result<BstNodeRef<BorrowType, Spec>, Self>
Examples found in repository?
crates/competitive/src/data_structure/binary_search_tree/node.rs (line 163)
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 }
237}
238
239pub struct BstNodeRef<BorrowType, Spec>
240where
241 Spec: BstSpec,
242{
243 pub node: NonNull<BstNode<Spec::Data, Spec::Parent>>,
244 _marker: PhantomData<BorrowType>,
245}
246
247impl<'a, Spec> Copy for BstNodeRef<marker::Immut<'a>, Spec> where Spec: BstSpec<Data: 'a> {}
248impl<'a, Spec> Clone for BstNodeRef<marker::Immut<'a>, Spec>
249where
250 Spec: BstSpec<Data: 'a>,
251{
252 fn clone(&self) -> Self {
253 *self
254 }
255}
256
257impl<BorrowType, Spec> BstNodeRef<BorrowType, Spec>
258where
259 Spec: BstSpec,
260 BorrowType: marker::BorrowType,
261{
262 pub unsafe fn new_unchecked(node: NonNull<BstNode<Spec::Data, Spec::Parent>>) -> Self {
263 Self {
264 node,
265 _marker: PhantomData,
266 }
267 }
268 pub fn reborrow(&self) -> BstNodeRef<marker::Immut<'_>, Spec> {
269 BstNodeRef {
270 node: self.node,
271 _marker: PhantomData,
272 }
273 }
274 pub fn left(self) -> BstEdgeHandle<Self, marker::Left> {
275 BstEdgeHandle {
276 node: self,
277 _marker: PhantomData,
278 }
279 }
280 pub fn right(self) -> BstEdgeHandle<Self, marker::Right> {
281 BstEdgeHandle {
282 node: self,
283 _marker: PhantomData,
284 }
285 }
286}
287
288impl<BorrowType, Spec, Data> BstNodeRef<BorrowType, Spec>
289where
290 Spec: BstSpec<Data = Data, Parent = WithParent<Data>>,
291 BorrowType: marker::BorrowType,
292{
293 pub fn ascend(self) -> Result<BstNodeRef<BorrowType, Spec>, Self> {
294 const {
295 assert!(BorrowType::TRAVERSAL_PERMIT);
296 };
297 let parent = unsafe { self.node.as_ref().parent.parent };
298 parent
299 .map(|node| BstNodeRef {
300 node,
301 _marker: PhantomData,
302 })
303 .ok_or(self)
304 }
305 pub fn root_path(self) -> (Self, Vec<bool>) {
306 let mut node = self;
307 let mut nn = node.node;
308 let mut stack = vec![];
309 let root = loop {
310 match node.ascend() {
311 Ok(parent) => {
312 node = parent;
313 stack.push(
314 node.reborrow()
315 .left()
316 .descend()
317 .is_ok_and(|node| node.node == nn),
318 );
319 nn = node.node;
320 }
321 Err(node) => {
322 break node;
323 }
324 }
325 };
326 (root, stack)
327 }Sourcepub fn root_path(self) -> (Self, Vec<bool>)
pub fn root_path(self) -> (Self, Vec<bool>)
Examples found in repository?
crates/competitive/src/data_structure/binary_search_tree/node.rs (line 144)
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 }Source§impl<Spec> BstNodeRef<Owned, Spec>where
Spec: BstSpec,
impl<Spec> BstNodeRef<Owned, Spec>where
Spec: BstSpec,
Sourcepub fn new(node: NonNull<BstNode<Spec::Data, Spec::Parent>>) -> Self
pub fn new(node: NonNull<BstNode<Spec::Data, Spec::Parent>>) -> Self
Examples found in repository?
More examples
crates/competitive/src/data_structure/implicit_splay_tree.rs (line 431)
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/splay_operations.rs (line 376)
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}Sourcepub fn from_data<A>(data: Spec::Data, allocator: &mut A) -> Self
pub fn from_data<A>(data: Spec::Data, allocator: &mut A) -> Self
Examples found in repository?
More examples
crates/competitive/src/data_structure/treap.rs (line 374)
366 pub fn insert(&mut self, key: M::Key, value: L::Key) -> BstNodeId<TreapSpec<M, L>> {
367 let (left, right) =
368 TreapSpec::split(self.root.take(), SeekByKey::new(&key), EqualSide::Right);
369 let data = TreapData {
370 priority: self.rng.rand64(),
371 key: MonoidActElement::from_key(key),
372 value: LazyMapElement::from_key(value),
373 };
374 let node = BstRoot::from_data(data, self.allocator.deref_mut());
375 let node_id = self.node_id_manager.register(&node);
376 self.root = TreapSpec::merge(TreapSpec::merge(left, Some(node)), right);
377 node_id
378 }crates/competitive/src/data_structure/splay_tree.rs (lines 249-256)
232 pub fn insert(&mut self, key: K, value: V) -> Option<V>
233 where
234 K: Ord,
235 {
236 let ordering = self.splay_by_key(&key);
237 if matches!(ordering, Some(Ordering::Equal)) {
238 return Some(replace(
239 &mut self
240 .root
241 .as_mut()
242 .unwrap()
243 .borrow_datamut()
244 .data_mut()
245 .value,
246 value,
247 ));
248 }
249 let mut node = BstRoot::from_data(
250 SplayTreeData {
251 key,
252 value,
253 size: 1,
254 },
255 self.allocator.deref_mut(),
256 );
257 if let Some(mut root) = self.root.take() {
258 match ordering.unwrap() {
259 Ordering::Greater => {
260 let left = unsafe { root.borrow_mut().left_mut().take() };
261 if let Some(left) = left {
262 unsafe { node.borrow_mut().left_mut().set(left) };
263 }
264 SplayTreeSpec::bottom_up(root.borrow_datamut());
265 unsafe { node.borrow_mut().right_mut().set(root) };
266 }
267 Ordering::Less => {
268 let right = unsafe { root.borrow_mut().right_mut().take() };
269 if let Some(right) = right {
270 unsafe { node.borrow_mut().right_mut().set(right) };
271 }
272 SplayTreeSpec::bottom_up(root.borrow_datamut());
273 unsafe { node.borrow_mut().left_mut().set(root) };
274 }
275 Ordering::Equal => unreachable!(),
276 }
277 SplayTreeSpec::bottom_up(node.borrow_datamut());
278 }
279 self.root = Some(node);
280 self.length += 1;
281 None
282 }Sourcepub fn borrow_mut(&mut self) -> BstNodeRef<Mut<'_>, Spec>
pub fn borrow_mut(&mut self) -> BstNodeRef<Mut<'_>, Spec>
Examples found in repository?
crates/competitive/src/data_structure/binary_search_tree/node.rs (line 185)
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 }
237}
238
239pub struct BstNodeRef<BorrowType, Spec>
240where
241 Spec: BstSpec,
242{
243 pub node: NonNull<BstNode<Spec::Data, Spec::Parent>>,
244 _marker: PhantomData<BorrowType>,
245}
246
247impl<'a, Spec> Copy for BstNodeRef<marker::Immut<'a>, Spec> where Spec: BstSpec<Data: 'a> {}
248impl<'a, Spec> Clone for BstNodeRef<marker::Immut<'a>, Spec>
249where
250 Spec: BstSpec<Data: 'a>,
251{
252 fn clone(&self) -> Self {
253 *self
254 }
255}
256
257impl<BorrowType, Spec> BstNodeRef<BorrowType, Spec>
258where
259 Spec: BstSpec,
260 BorrowType: marker::BorrowType,
261{
262 pub unsafe fn new_unchecked(node: NonNull<BstNode<Spec::Data, Spec::Parent>>) -> Self {
263 Self {
264 node,
265 _marker: PhantomData,
266 }
267 }
268 pub fn reborrow(&self) -> BstNodeRef<marker::Immut<'_>, Spec> {
269 BstNodeRef {
270 node: self.node,
271 _marker: PhantomData,
272 }
273 }
274 pub fn left(self) -> BstEdgeHandle<Self, marker::Left> {
275 BstEdgeHandle {
276 node: self,
277 _marker: PhantomData,
278 }
279 }
280 pub fn right(self) -> BstEdgeHandle<Self, marker::Right> {
281 BstEdgeHandle {
282 node: self,
283 _marker: PhantomData,
284 }
285 }
286}
287
288impl<BorrowType, Spec, Data> BstNodeRef<BorrowType, Spec>
289where
290 Spec: BstSpec<Data = Data, Parent = WithParent<Data>>,
291 BorrowType: marker::BorrowType,
292{
293 pub fn ascend(self) -> Result<BstNodeRef<BorrowType, Spec>, Self> {
294 const {
295 assert!(BorrowType::TRAVERSAL_PERMIT);
296 };
297 let parent = unsafe { self.node.as_ref().parent.parent };
298 parent
299 .map(|node| BstNodeRef {
300 node,
301 _marker: PhantomData,
302 })
303 .ok_or(self)
304 }
305 pub fn root_path(self) -> (Self, Vec<bool>) {
306 let mut node = self;
307 let mut nn = node.node;
308 let mut stack = vec![];
309 let root = loop {
310 match node.ascend() {
311 Ok(parent) => {
312 node = parent;
313 stack.push(
314 node.reborrow()
315 .left()
316 .descend()
317 .is_ok_and(|node| node.node == nn),
318 );
319 nn = node.node;
320 }
321 Err(node) => {
322 break node;
323 }
324 }
325 };
326 (root, stack)
327 }
328}
329
330impl<Spec> BstNodeRef<marker::Owned, Spec>
331where
332 Spec: BstSpec,
333{
334 pub fn new(node: NonNull<BstNode<Spec::Data, Spec::Parent>>) -> Self {
335 Self {
336 node,
337 _marker: PhantomData,
338 }
339 }
340 pub fn from_data<A>(data: Spec::Data, allocator: &mut A) -> Self
341 where
342 A: Allocator<BstNode<Spec::Data, Spec::Parent>>,
343 {
344 Self::new(allocator.allocate(BstNode::new(data)))
345 }
346 pub fn borrow_mut(&mut self) -> BstNodeRef<marker::Mut<'_>, Spec> {
347 BstNodeRef {
348 node: self.node,
349 _marker: PhantomData,
350 }
351 }
352 pub fn borrow_datamut(&mut self) -> BstNodeRef<marker::DataMut<'_>, Spec> {
353 BstNodeRef {
354 node: self.node,
355 _marker: PhantomData,
356 }
357 }
358 pub fn into_dying(self) -> BstNodeRef<marker::Dying, Spec> {
359 BstNodeRef {
360 node: self.node,
361 _marker: PhantomData,
362 }
363 }
364}
365
366impl<'a, Spec> BstNodeRef<marker::Immut<'a>, Spec>
367where
368 Spec: BstSpec<Parent: 'a, Data: 'a>,
369{
370 pub fn into_data(self) -> &'a Spec::Data {
371 unsafe { &self.node.as_ref().data }
372 }
373
374 pub fn traverse<F>(self, f: &mut F)
375 where
376 F: FnMut(Self),
377 {
378 if let Ok(left) = self.left().descend() {
379 left.traverse(f);
380 }
381 f(self);
382 if let Ok(right) = self.right().descend() {
383 right.traverse(f);
384 }
385 }
386
387 pub fn leftmost(self) -> Self {
388 let mut node = self;
389 while let Ok(left) = node.left().descend() {
390 node = left;
391 }
392 node
393 }
394
395 pub fn rightmost(self) -> Self {
396 let mut node = self;
397 while let Ok(right) = node.right().descend() {
398 node = right;
399 }
400 node
401 }
402}
403
404impl<'a, Spec> BstNodeRef<marker::DataMut<'a>, Spec>
405where
406 Spec: BstSpec,
407{
408 pub fn reborrow_datamut(&mut self) -> BstNodeRef<marker::DataMut<'_>, Spec> {
409 BstNodeRef {
410 node: self.node,
411 _marker: PhantomData,
412 }
413 }
414 pub fn data_mut(&mut self) -> &mut Spec::Data {
415 unsafe { &mut self.node.as_mut().data }
416 }
417
418 pub fn swap_children(&mut self) {
419 unsafe { self.node.as_mut().child.swap(0, 1) };
420 }
421}
422
423impl<'a, Spec> BstNodeRef<marker::DataMut<'a>, Spec>
424where
425 Spec: BstSpec<Parent: 'a, Data: 'a>,
426{
427 pub fn into_data_mut(mut self) -> &'a mut Spec::Data {
428 unsafe { &mut self.node.as_mut().data }
429 }
430}
431
432impl<'a, Spec> BstNodeRef<marker::Mut<'a>, Spec>
433where
434 Spec: BstSpec,
435{
436 pub fn reborrow_datamut(&mut self) -> BstNodeRef<marker::DataMut<'_>, Spec> {
437 BstNodeRef {
438 node: self.node,
439 _marker: PhantomData,
440 }
441 }
442
443 pub fn left_mut(&mut self) -> BstEdgeHandle<BstNodeRef<marker::Mut<'_>, Spec>, marker::Left> {
444 BstEdgeHandle {
445 node: BstNodeRef {
446 node: self.node,
447 _marker: PhantomData,
448 },
449 _marker: PhantomData,
450 }
451 }
452
453 pub fn right_mut(&mut self) -> BstEdgeHandle<BstNodeRef<marker::Mut<'_>, Spec>, marker::Right> {
454 BstEdgeHandle {
455 node: BstNodeRef {
456 node: self.node,
457 _marker: PhantomData,
458 },
459 _marker: PhantomData,
460 }
461 }
462}
463
464impl<'a, Spec> BstNodeRef<marker::Mut<'a>, Spec>
465where
466 Spec: BstSpec<Data: 'a>,
467{
468 pub fn dormant(self) -> BstNodeRef<marker::DormantMut, Spec> {
469 BstNodeRef {
470 node: self.node,
471 _marker: PhantomData,
472 }
473 }
474}
475
476impl<Spec> BstNodeRef<marker::DormantMut, Spec>
477where
478 Spec: BstSpec,
479{
480 pub unsafe fn awaken<'a>(self) -> BstNodeRef<marker::Mut<'a>, Spec> {
481 BstNodeRef {
482 node: self.node,
483 _marker: PhantomData,
484 }
485 }
486}
487
488impl<Spec> BstNodeRef<marker::Dying, Spec>
489where
490 Spec: BstSpec,
491{
492 pub unsafe fn into_data<A>(self, allocator: &mut A) -> Spec::Data
493 where
494 A: Allocator<BstNode<Spec::Data, Spec::Parent>>,
495 {
496 debug_assert!(self.reborrow().left().descend().is_err());
497 debug_assert!(self.reborrow().right().descend().is_err());
498 allocator.deallocate(self.node).data
499 }
500
501 pub unsafe fn drop_all<A>(self, allocator: &mut A)
502 where
503 A: Allocator<BstNode<Spec::Data, Spec::Parent>>,
504 {
505 let mut stack = vec![self.node];
506 while let Some(node) = stack.pop() {
507 stack.extend(allocator.deallocate(node).child.into_iter().flatten());
508 }
509 }
510}
511
512pub struct BstEdgeHandle<Node, Dir> {
513 node: Node,
514 _marker: PhantomData<Dir>,
515}
516
517impl<BorrowType, Spec, Dir> BstEdgeHandle<BstNodeRef<BorrowType, Spec>, Dir>
518where
519 Spec: BstSpec,
520 BorrowType: marker::BorrowType,
521 Dir: marker::BstDirection,
522{
523 pub fn descend(self) -> Result<BstNodeRef<BorrowType, Spec>, Self> {
524 const {
525 assert!(BorrowType::TRAVERSAL_PERMIT);
526 };
527 let child = unsafe { self.node.node.as_ref().child.get_unchecked(Dir::IDX) };
528 child
529 .map(|node| BstNodeRef {
530 node,
531 _marker: PhantomData,
532 })
533 .ok_or(self)
534 }
535}
536
537impl<'a, Spec, Dir> BstEdgeHandle<BstNodeRef<marker::Mut<'a>, Spec>, Dir>
538where
539 Spec: BstSpec,
540 Dir: marker::BstDirection,
541{
542 pub unsafe fn take(&mut self) -> Option<BstNodeRef<marker::Owned, Spec>> {
543 let child = unsafe { self.node.node.as_mut().child.get_unchecked_mut(Dir::IDX) };
544 child.take().map(|node| {
545 let mut node = BstNodeRef {
546 node,
547 _marker: PhantomData,
548 };
549 Spec::Parent::take_parent(node.borrow_mut());
550 node
551 })
552 }
553 pub unsafe fn replace(
554 &mut self,
555 mut other: BstNodeRef<marker::Owned, Spec>,
556 ) -> Option<BstNodeRef<marker::Owned, Spec>> {
557 let child = unsafe { self.node.node.as_mut().child.get_unchecked_mut(Dir::IDX) };
558 Spec::Parent::set_parent(other.borrow_mut(), Some(self.node.node));
559 child.replace(other.node).map(|node| {
560 let mut node = BstNodeRef {
561 node,
562 _marker: PhantomData,
563 };
564 Spec::Parent::take_parent(node.borrow_mut());
565 node
566 })
567 }
568 pub unsafe fn set(&mut self, mut other: BstNodeRef<marker::Owned, Spec>) {
569 let child = unsafe { self.node.node.as_mut().child.get_unchecked_mut(Dir::IDX) };
570 Spec::Parent::set_parent(other.borrow_mut(), Some(self.node.node));
571 *child = Some(other.node);
572 }More examples
crates/competitive/src/data_structure/implicit_splay_tree.rs (line 327)
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 162)
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 }crates/competitive/src/data_structure/treap.rs (line 127)
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 }crates/competitive/src/data_structure/splay_tree.rs (line 260)
232 pub fn insert(&mut self, key: K, value: V) -> Option<V>
233 where
234 K: Ord,
235 {
236 let ordering = self.splay_by_key(&key);
237 if matches!(ordering, Some(Ordering::Equal)) {
238 return Some(replace(
239 &mut self
240 .root
241 .as_mut()
242 .unwrap()
243 .borrow_datamut()
244 .data_mut()
245 .value,
246 value,
247 ));
248 }
249 let mut node = BstRoot::from_data(
250 SplayTreeData {
251 key,
252 value,
253 size: 1,
254 },
255 self.allocator.deref_mut(),
256 );
257 if let Some(mut root) = self.root.take() {
258 match ordering.unwrap() {
259 Ordering::Greater => {
260 let left = unsafe { root.borrow_mut().left_mut().take() };
261 if let Some(left) = left {
262 unsafe { node.borrow_mut().left_mut().set(left) };
263 }
264 SplayTreeSpec::bottom_up(root.borrow_datamut());
265 unsafe { node.borrow_mut().right_mut().set(root) };
266 }
267 Ordering::Less => {
268 let right = unsafe { root.borrow_mut().right_mut().take() };
269 if let Some(right) = right {
270 unsafe { node.borrow_mut().right_mut().set(right) };
271 }
272 SplayTreeSpec::bottom_up(root.borrow_datamut());
273 unsafe { node.borrow_mut().left_mut().set(root) };
274 }
275 Ordering::Equal => unreachable!(),
276 }
277 SplayTreeSpec::bottom_up(node.borrow_datamut());
278 }
279 self.root = Some(node);
280 self.length += 1;
281 None
282 }
283
284 pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
285 where
286 K: Borrow<Q>,
287 Q: Ord + ?Sized,
288 {
289 if !matches!(self.splay_by_key(key)?, Ordering::Equal) {
290 return None;
291 }
292 Some(self.remove_root().1)
293 }
294
295 pub fn remove_at(&mut self, index: usize) -> Option<(K, V)> {
296 if index >= self.length {
297 return None;
298 }
299 self.splay_by_size(index);
300 Some(self.remove_root())
301 }
302
303 fn remove_root(&mut self) -> (K, V) {
304 let mut node = self.root.take().unwrap();
305 let left = unsafe { node.borrow_mut().left_mut().take() };
306 let right = unsafe { node.borrow_mut().right_mut().take() };
307 self.root = SplayTreeSpec::merge(left, right);
308 self.length -= 1;
309 let data = unsafe { node.into_dying().into_data(self.allocator.deref_mut()) };
310 (data.key, data.value)
311 }crates/competitive/src/data_structure/splay_operations.rs (line 279)
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}Sourcepub fn borrow_datamut(&mut self) -> BstNodeRef<DataMut<'_>, Spec>
pub fn borrow_datamut(&mut self) -> BstNodeRef<DataMut<'_>, Spec>
Examples found in repository?
crates/competitive/src/data_structure/binary_search_tree/split.rs (line 49)
48 pub fn left_datamut(&mut self) -> Option<BstDataMutRef<'_, Spec>> {
49 self.left.as_mut().map(|node| node.borrow_datamut())
50 }
51
52 pub fn right_datamut(&mut self) -> Option<BstDataMutRef<'_, Spec>> {
53 self.right.as_mut().map(|node| node.borrow_datamut())
54 }
55
56 pub fn manually_merge<F>(&mut self, mut f: F)
57 where
58 F: FnMut(Option<BstRoot<Spec>>, Option<BstRoot<Spec>>) -> Option<BstRoot<Spec>>,
59 {
60 self.left = f(self.left.take(), self.right.take());
61 }
62}
63
64impl<'a, Spec> Drop for Split<'a, Spec>
65where
66 Spec: BstSpec,
67{
68 fn drop(&mut self) {
69 *self.root = Spec::merge(self.left.take(), self.right.take());
70 }
71}
72
73pub struct Split3<'a, Spec>
74where
75 Spec: BstSpec,
76{
77 left: Option<BstRoot<Spec>>,
78 mid: Option<BstRoot<Spec>>,
79 right: Option<BstRoot<Spec>>,
80 root: &'a mut Option<BstRoot<Spec>>,
81}
82
83impl<'a, Spec> Split3<'a, Spec>
84where
85 Spec: BstSpec,
86{
87 pub fn new<Seek1, Seek2>(
88 node: &'a mut Option<BstRoot<Spec>>,
89 start: Bound<Seek1>,
90 end: Bound<Seek2>,
91 ) -> Self
92 where
93 Seek1: BstSeeker<Spec = Spec>,
94 Seek2: BstSeeker<Spec = Spec>,
95 {
96 let (mut rest, right) = match end {
97 Bound::Included(seeker) => Spec::split(node.take(), seeker, EqualSide::Left),
98 Bound::Excluded(seeker) => Spec::split(node.take(), seeker, EqualSide::Right),
99 Bound::Unbounded => (node.take(), None),
100 };
101 let (left, mid) = match start {
102 Bound::Included(seeker) => Spec::split(rest.take(), seeker, EqualSide::Right),
103 Bound::Excluded(seeker) => Spec::split(rest.take(), seeker, EqualSide::Left),
104 Bound::Unbounded => (None, rest),
105 };
106 Self {
107 left,
108 mid,
109 right,
110 root: node,
111 }
112 }
113
114 pub fn left(&self) -> Option<BstImmutRef<'_, Spec>> {
115 self.left.as_ref().map(|node| node.reborrow())
116 }
117
118 pub fn mid(&self) -> Option<BstImmutRef<'_, Spec>> {
119 self.mid.as_ref().map(|node| node.reborrow())
120 }
121
122 pub fn right(&self) -> Option<BstImmutRef<'_, Spec>> {
123 self.right.as_ref().map(|node| node.reborrow())
124 }
125
126 pub fn left_datamut(&mut self) -> Option<BstDataMutRef<'_, Spec>> {
127 self.left.as_mut().map(|node| node.borrow_datamut())
128 }
129
130 pub fn mid_datamut(&mut self) -> Option<BstDataMutRef<'_, Spec>> {
131 self.mid.as_mut().map(|node| node.borrow_datamut())
132 }
133
134 pub fn right_datamut(&mut self) -> Option<BstDataMutRef<'_, Spec>> {
135 self.right.as_mut().map(|node| node.borrow_datamut())
136 }More examples
crates/competitive/src/data_structure/implicit_splay_tree.rs (line 311)
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/binary_search_tree/node.rs (line 188)
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_treap.rs (line 161)
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/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 }
227}
228
229pub struct Treap<M, L, A = BoxAllocator<TreapNode<M, L>>>
230where
231 M: MonoidAct<Key: Ord>,
232 L: LazyMapMonoid,
233 A: Allocator<TreapNode<M, L>>,
234{
235 root: Option<TreapRoot<M, L>>,
236 node_id_manager: BstNodeIdManager<TreapSpec<M, L>>,
237 rng: Xorshift,
238 allocator: ManuallyDrop<A>,
239 _marker: PhantomData<(M, L)>,
240}
241
242impl<M, L, A> Default for Treap<M, L, A>
243where
244 M: MonoidAct<Key: Ord>,
245 L: LazyMapMonoid,
246 A: Allocator<TreapNode<M, L>> + Default,
247{
248 fn default() -> Self {
249 Self {
250 root: None,
251 node_id_manager: Default::default(),
252 rng: Xorshift::new(),
253 allocator: ManuallyDrop::new(A::default()),
254 _marker: PhantomData,
255 }
256 }
257}
258
259impl<M, L, A> Drop for Treap<M, L, A>
260where
261 M: MonoidAct<Key: Ord>,
262 L: LazyMapMonoid,
263 A: Allocator<TreapNode<M, L>>,
264{
265 fn drop(&mut self) {
266 unsafe {
267 if let Some(root) = self.root.take() {
268 root.into_dying().drop_all(self.allocator.deref_mut());
269 }
270 ManuallyDrop::drop(&mut self.allocator);
271 }
272 }
273}
274
275impl<M, L> Treap<M, L>
276where
277 M: MonoidAct<Key: Ord>,
278 L: LazyMapMonoid,
279{
280 pub fn new() -> Self {
281 Self::default()
282 }
283}
284
285impl<M, L, A> Treap<M, L, A>
286where
287 M: MonoidAct<Key: Ord>,
288 L: LazyMapMonoid,
289 A: Allocator<TreapNode<M, L>>,
290{
291 pub fn len(&self) -> usize {
292 self.node_id_manager.len()
293 }
294
295 pub fn is_empty(&self) -> bool {
296 self.node_id_manager.is_empty()
297 }
298
299 pub fn clear(&mut self) {
300 unsafe {
301 if let Some(root) = self.root.take() {
302 root.into_dying().drop_all(self.allocator.deref_mut());
303 }
304 self.node_id_manager.clear();
305 }
306 }
307
308 pub fn get(&mut self, node_id: BstNodeId<TreapSpec<M, L>>) -> Option<(&M::Key, &L::Key)> {
309 if !self.node_id_manager.contains(&node_id) {
310 return None;
311 }
312 unsafe {
313 WithParent::resolve_top_down::<TreapSpec<M, L>>(
314 node_id.reborrow_datamut(&mut self.root),
315 );
316 let data = node_id.reborrow(&self.root).into_data();
317 Some((&data.key.key, &data.value.key))
318 }
319 }
320
321 pub fn change(
322 &mut self,
323 node_id: BstNodeId<TreapSpec<M, L>>,
324 f: impl FnOnce(&mut L::Key),
325 ) -> bool {
326 if !self.node_id_manager.contains(&node_id) {
327 return false;
328 }
329 unsafe {
330 WithParent::resolve_top_down::<TreapSpec<M, L>>(
331 node_id.reborrow_datamut(&mut self.root),
332 );
333 let data = node_id.reborrow_datamut(&mut self.root).into_data_mut();
334 f(&mut data.value.key);
335 WithParent::resolve_bottom_up::<TreapSpec<M, L>>(
336 node_id.reborrow_datamut(&mut self.root),
337 );
338 }
339 true
340 }
341
342 pub fn change_key_value(
343 &mut self,
344 node_id: BstNodeId<TreapSpec<M, L>>,
345 f: impl FnOnce(&mut M::Key, &mut L::Key),
346 ) -> bool {
347 if !self.node_id_manager.contains(&node_id) {
348 return false;
349 }
350 unsafe {
351 WithParent::resolve_top_down::<TreapSpec<M, L>>(
352 node_id.reborrow_datamut(&mut self.root),
353 );
354 let mut node = if WithParent::is_root(node_id.reborrow(&self.root)) {
355 WithParent::remove_root(&mut self.root).unwrap_unchecked()
356 } else {
357 WithParent::remove_not_root(node_id.reborrow_mut(&mut self.root))
358 };
359 let data = node.borrow_datamut().into_data_mut();
360 f(&mut data.key.key, &mut data.value.key);
361 self.root = TreapSpec::merge_ordered(self.root.take(), Some(node));
362 true
363 }
364 }crates/competitive/src/data_structure/splay_tree.rs (line 243)
232 pub fn insert(&mut self, key: K, value: V) -> Option<V>
233 where
234 K: Ord,
235 {
236 let ordering = self.splay_by_key(&key);
237 if matches!(ordering, Some(Ordering::Equal)) {
238 return Some(replace(
239 &mut self
240 .root
241 .as_mut()
242 .unwrap()
243 .borrow_datamut()
244 .data_mut()
245 .value,
246 value,
247 ));
248 }
249 let mut node = BstRoot::from_data(
250 SplayTreeData {
251 key,
252 value,
253 size: 1,
254 },
255 self.allocator.deref_mut(),
256 );
257 if let Some(mut root) = self.root.take() {
258 match ordering.unwrap() {
259 Ordering::Greater => {
260 let left = unsafe { root.borrow_mut().left_mut().take() };
261 if let Some(left) = left {
262 unsafe { node.borrow_mut().left_mut().set(left) };
263 }
264 SplayTreeSpec::bottom_up(root.borrow_datamut());
265 unsafe { node.borrow_mut().right_mut().set(root) };
266 }
267 Ordering::Less => {
268 let right = unsafe { root.borrow_mut().right_mut().take() };
269 if let Some(right) = right {
270 unsafe { node.borrow_mut().right_mut().set(right) };
271 }
272 SplayTreeSpec::bottom_up(root.borrow_datamut());
273 unsafe { node.borrow_mut().left_mut().set(root) };
274 }
275 Ordering::Equal => unreachable!(),
276 }
277 SplayTreeSpec::bottom_up(node.borrow_datamut());
278 }
279 self.root = Some(node);
280 self.length += 1;
281 None
282 }Additional examples can be found in:
Sourcepub fn into_dying(self) -> BstNodeRef<Dying, Spec>
pub fn into_dying(self) -> BstNodeRef<Dying, Spec>
Examples found in repository?
crates/competitive/src/data_structure/implicit_splay_tree.rs (line 207)
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 }More examples
crates/competitive/src/data_structure/implicit_treap.rs (line 253)
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/splay_tree.rs (line 157)
154 fn drop(&mut self) {
155 unsafe {
156 if let Some(root) = self.root.take() {
157 root.into_dying().drop_all(self.allocator.deref_mut());
158 }
159 ManuallyDrop::drop(&mut self.allocator);
160 }
161 }
162}
163
164impl<K, V> SplayTree<K, V> {
165 pub fn new() -> Self {
166 Self::default()
167 }
168
169 pub fn with_capacity(capacity: usize) -> Self {
170 Self {
171 root: None,
172 length: 0,
173 allocator: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
174 }
175 }
176}
177
178impl<K, V, A> SplayTree<K, V, A>
179where
180 A: Allocator<SplayTreeNode<K, V>>,
181{
182 #[inline]
183 fn splay<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
184 where
185 Seeker: BstSeeker<Spec = SplayTreeSpec<K, V>>,
186 {
187 let (ordering, root) = splay_operations::splay(self.root.take()?, seeker);
188 self.root = Some(root);
189 Some(ordering)
190 }
191
192 fn splay_by_key<Q>(&mut self, key: &Q) -> Option<Ordering>
193 where
194 K: Borrow<Q>,
195 Q: Ord + ?Sized,
196 {
197 self.splay(SeekByKey::new(key))
198 }
199
200 fn splay_by_size(&mut self, index: usize) -> Option<Ordering> {
201 self.splay(SeekBySize::new(index))
202 }
203
204 pub fn get<Q>(&mut self, key: &Q) -> Option<&V>
205 where
206 K: Borrow<Q>,
207 Q: Ord + ?Sized,
208 {
209 self.get_key_value(key).map(|(_, value)| value)
210 }
211
212 pub fn get_key_value<Q>(&mut self, key: &Q) -> Option<(&K, &V)>
213 where
214 K: Borrow<Q>,
215 Q: Ord + ?Sized,
216 {
217 matches!(self.splay_by_key(key)?, Ordering::Equal).then(|| {
218 let data = self.root.as_ref().unwrap().reborrow().into_data();
219 (&data.key, &data.value)
220 })
221 }
222
223 pub fn get_key_value_at(&mut self, index: usize) -> Option<(&K, &V)> {
224 if index >= self.length {
225 return None;
226 }
227 self.splay_by_size(index);
228 let data = self.root.as_ref()?.reborrow().into_data();
229 Some((&data.key, &data.value))
230 }
231
232 pub fn insert(&mut self, key: K, value: V) -> Option<V>
233 where
234 K: Ord,
235 {
236 let ordering = self.splay_by_key(&key);
237 if matches!(ordering, Some(Ordering::Equal)) {
238 return Some(replace(
239 &mut self
240 .root
241 .as_mut()
242 .unwrap()
243 .borrow_datamut()
244 .data_mut()
245 .value,
246 value,
247 ));
248 }
249 let mut node = BstRoot::from_data(
250 SplayTreeData {
251 key,
252 value,
253 size: 1,
254 },
255 self.allocator.deref_mut(),
256 );
257 if let Some(mut root) = self.root.take() {
258 match ordering.unwrap() {
259 Ordering::Greater => {
260 let left = unsafe { root.borrow_mut().left_mut().take() };
261 if let Some(left) = left {
262 unsafe { node.borrow_mut().left_mut().set(left) };
263 }
264 SplayTreeSpec::bottom_up(root.borrow_datamut());
265 unsafe { node.borrow_mut().right_mut().set(root) };
266 }
267 Ordering::Less => {
268 let right = unsafe { root.borrow_mut().right_mut().take() };
269 if let Some(right) = right {
270 unsafe { node.borrow_mut().right_mut().set(right) };
271 }
272 SplayTreeSpec::bottom_up(root.borrow_datamut());
273 unsafe { node.borrow_mut().left_mut().set(root) };
274 }
275 Ordering::Equal => unreachable!(),
276 }
277 SplayTreeSpec::bottom_up(node.borrow_datamut());
278 }
279 self.root = Some(node);
280 self.length += 1;
281 None
282 }
283
284 pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
285 where
286 K: Borrow<Q>,
287 Q: Ord + ?Sized,
288 {
289 if !matches!(self.splay_by_key(key)?, Ordering::Equal) {
290 return None;
291 }
292 Some(self.remove_root().1)
293 }
294
295 pub fn remove_at(&mut self, index: usize) -> Option<(K, V)> {
296 if index >= self.length {
297 return None;
298 }
299 self.splay_by_size(index);
300 Some(self.remove_root())
301 }
302
303 fn remove_root(&mut self) -> (K, V) {
304 let mut node = self.root.take().unwrap();
305 let left = unsafe { node.borrow_mut().left_mut().take() };
306 let right = unsafe { node.borrow_mut().right_mut().take() };
307 self.root = SplayTreeSpec::merge(left, right);
308 self.length -= 1;
309 let data = unsafe { node.into_dying().into_data(self.allocator.deref_mut()) };
310 (data.key, data.value)
311 }crates/competitive/src/data_structure/treap.rs (line 268)
265 fn drop(&mut self) {
266 unsafe {
267 if let Some(root) = self.root.take() {
268 root.into_dying().drop_all(self.allocator.deref_mut());
269 }
270 ManuallyDrop::drop(&mut self.allocator);
271 }
272 }
273}
274
275impl<M, L> Treap<M, L>
276where
277 M: MonoidAct<Key: Ord>,
278 L: LazyMapMonoid,
279{
280 pub fn new() -> Self {
281 Self::default()
282 }
283}
284
285impl<M, L, A> Treap<M, L, A>
286where
287 M: MonoidAct<Key: Ord>,
288 L: LazyMapMonoid,
289 A: Allocator<TreapNode<M, L>>,
290{
291 pub fn len(&self) -> usize {
292 self.node_id_manager.len()
293 }
294
295 pub fn is_empty(&self) -> bool {
296 self.node_id_manager.is_empty()
297 }
298
299 pub fn clear(&mut self) {
300 unsafe {
301 if let Some(root) = self.root.take() {
302 root.into_dying().drop_all(self.allocator.deref_mut());
303 }
304 self.node_id_manager.clear();
305 }
306 }
307
308 pub fn get(&mut self, node_id: BstNodeId<TreapSpec<M, L>>) -> Option<(&M::Key, &L::Key)> {
309 if !self.node_id_manager.contains(&node_id) {
310 return None;
311 }
312 unsafe {
313 WithParent::resolve_top_down::<TreapSpec<M, L>>(
314 node_id.reborrow_datamut(&mut self.root),
315 );
316 let data = node_id.reborrow(&self.root).into_data();
317 Some((&data.key.key, &data.value.key))
318 }
319 }
320
321 pub fn change(
322 &mut self,
323 node_id: BstNodeId<TreapSpec<M, L>>,
324 f: impl FnOnce(&mut L::Key),
325 ) -> bool {
326 if !self.node_id_manager.contains(&node_id) {
327 return false;
328 }
329 unsafe {
330 WithParent::resolve_top_down::<TreapSpec<M, L>>(
331 node_id.reborrow_datamut(&mut self.root),
332 );
333 let data = node_id.reborrow_datamut(&mut self.root).into_data_mut();
334 f(&mut data.value.key);
335 WithParent::resolve_bottom_up::<TreapSpec<M, L>>(
336 node_id.reborrow_datamut(&mut self.root),
337 );
338 }
339 true
340 }
341
342 pub fn change_key_value(
343 &mut self,
344 node_id: BstNodeId<TreapSpec<M, L>>,
345 f: impl FnOnce(&mut M::Key, &mut L::Key),
346 ) -> bool {
347 if !self.node_id_manager.contains(&node_id) {
348 return false;
349 }
350 unsafe {
351 WithParent::resolve_top_down::<TreapSpec<M, L>>(
352 node_id.reborrow_datamut(&mut self.root),
353 );
354 let mut node = if WithParent::is_root(node_id.reborrow(&self.root)) {
355 WithParent::remove_root(&mut self.root).unwrap_unchecked()
356 } else {
357 WithParent::remove_not_root(node_id.reborrow_mut(&mut self.root))
358 };
359 let data = node.borrow_datamut().into_data_mut();
360 f(&mut data.key.key, &mut data.value.key);
361 self.root = TreapSpec::merge_ordered(self.root.take(), Some(node));
362 true
363 }
364 }
365
366 pub fn insert(&mut self, key: M::Key, value: L::Key) -> BstNodeId<TreapSpec<M, L>> {
367 let (left, right) =
368 TreapSpec::split(self.root.take(), SeekByKey::new(&key), EqualSide::Right);
369 let data = TreapData {
370 priority: self.rng.rand64(),
371 key: MonoidActElement::from_key(key),
372 value: LazyMapElement::from_key(value),
373 };
374 let node = BstRoot::from_data(data, self.allocator.deref_mut());
375 let node_id = self.node_id_manager.register(&node);
376 self.root = TreapSpec::merge(TreapSpec::merge(left, Some(node)), right);
377 node_id
378 }
379
380 pub fn remove(&mut self, node_id: BstNodeId<TreapSpec<M, L>>) -> Option<(M::Key, L::Key)> {
381 if !self.node_id_manager.contains(&node_id) {
382 return None;
383 }
384 unsafe {
385 WithParent::resolve_top_down::<TreapSpec<M, L>>(
386 node_id.reborrow_datamut(&mut self.root),
387 );
388 let node = if WithParent::is_root(node_id.reborrow(&self.root)) {
389 WithParent::remove_root(&mut self.root).unwrap_unchecked()
390 } else {
391 WithParent::remove_not_root(node_id.reborrow_mut(&mut self.root))
392 };
393 self.node_id_manager.unregister(node_id);
394 let data = node.into_dying().into_data(self.allocator.deref_mut());
395 Some((data.key.key, data.value.key))
396 }
397 }Source§impl<'a, Spec> BstNodeRef<Immut<'a>, Spec>where
Spec: BstSpec<Parent: 'a, Data: 'a>,
impl<'a, Spec> BstNodeRef<Immut<'a>, Spec>where
Spec: BstSpec<Parent: 'a, Data: 'a>,
Sourcepub fn into_data(self) -> &'a Spec::Data
pub fn into_data(self) -> &'a Spec::Data
Examples found in repository?
crates/competitive/src/data_structure/binary_search_tree/seeker.rs (line 93)
91 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
92 node.reborrow()
93 .into_data()
94 .bst_data()
95 .borrow()
96 .cmp(self.key)
97 }
98}
99
100pub struct SeekBySize<Spec> {
101 index: usize,
102 _marker: PhantomData<fn() -> Spec>,
103}
104
105impl<Spec> SeekBySize<Spec> {
106 pub fn new(index: usize) -> Self {
107 Self {
108 index,
109 _marker: PhantomData,
110 }
111 }
112}
113
114impl<Spec> BstSeeker for SeekBySize<Spec>
115where
116 Spec: BstSpec<Data: BstDataAccess<data::marker::Size, Value = usize>>,
117{
118 type Spec = Spec;
119
120 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
121 let lsize = node
122 .reborrow()
123 .left()
124 .descend()
125 .map(|l| *l.into_data().bst_data())
126 .unwrap_or_default();
127 let ord = lsize.cmp(&self.index);
128 if matches!(ord, Ordering::Less) {
129 self.index -= lsize + 1;
130 }
131 ord
132 }
133}
134
135pub struct SeekByAccCond<Spec, L, F>
136where
137 L: LazyMapMonoid,
138{
139 acc: L::Agg,
140 f: F,
141 _marker: PhantomData<fn() -> (Spec, L)>,
142}
143
144impl<Spec, L, F> SeekByAccCond<Spec, L, F>
145where
146 L: LazyMapMonoid,
147 F: FnMut(&L::Agg) -> bool,
148{
149 pub fn new(f: F) -> Self {
150 Self {
151 acc: L::agg_unit(),
152 f,
153 _marker: PhantomData,
154 }
155 }
156}
157
158impl<Spec, L, F> BstSeeker for SeekByAccCond<Spec, L, F>
159where
160 Spec: BstSpec<Data: BstDataAccess<data::marker::LazyMap, Value = LazyMapElement<L>>>,
161 L: LazyMapMonoid,
162 F: FnMut(&L::Agg) -> bool,
163{
164 type Spec = Spec;
165
166 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
167 if let Ok(left) = node.reborrow().left().descend() {
168 let left_agg = &left.into_data().bst_data().agg;
169 let nagg = L::agg_operate(&self.acc, left_agg);
170 if (self.f)(&nagg) {
171 return Ordering::Greater;
172 }
173 let nagg = L::agg_operate(
174 &nagg,
175 &L::single_agg(&node.reborrow().into_data().bst_data().key),
176 );
177 if (self.f)(&nagg) {
178 Ordering::Equal
179 } else {
180 self.acc = nagg;
181 Ordering::Less
182 }
183 } else {
184 let nagg = L::agg_operate(
185 &self.acc,
186 &L::single_agg(&node.reborrow().into_data().bst_data().key),
187 );
188 if (self.f)(&nagg) {
189 Ordering::Equal
190 } else {
191 self.acc = nagg;
192 Ordering::Less
193 }
194 }
195 }
196}
197
198pub struct SeekByRaccCond<Spec, L, F>
199where
200 L: LazyMapMonoid,
201{
202 acc: L::Agg,
203 f: F,
204 _marker: PhantomData<fn() -> (Spec, L)>,
205}
206
207impl<Spec, L, F> SeekByRaccCond<Spec, L, F>
208where
209 L: LazyMapMonoid,
210 F: FnMut(&L::Agg) -> bool,
211{
212 pub fn new(f: F) -> Self {
213 Self {
214 acc: L::agg_unit(),
215 f,
216 _marker: PhantomData,
217 }
218 }
219}
220
221impl<Spec, L, F> BstSeeker for SeekByRaccCond<Spec, L, F>
222where
223 Spec: BstSpec<Data: BstDataAccess<data::marker::LazyMap, Value = LazyMapElement<L>>>,
224 L: LazyMapMonoid,
225 F: FnMut(&L::Agg) -> bool,
226{
227 type Spec = Spec;
228
229 fn bst_seek(&mut self, node: BstImmutRef<'_, Self::Spec>) -> Ordering {
230 if let Ok(right) = node.reborrow().right().descend() {
231 let right_agg = &right.into_data().bst_data().agg;
232 let nagg = L::agg_operate(right_agg, &self.acc);
233 if (self.f)(&nagg) {
234 return Ordering::Less;
235 }
236 let nagg = L::agg_operate(
237 &L::single_agg(&node.reborrow().into_data().bst_data().key),
238 &nagg,
239 );
240 if (self.f)(&nagg) {
241 Ordering::Equal
242 } else {
243 self.acc = nagg;
244 Ordering::Greater
245 }
246 } else {
247 let nagg = L::agg_operate(
248 &L::single_agg(&node.reborrow().into_data().bst_data().key),
249 &self.acc,
250 );
251 if (self.f)(&nagg) {
252 Ordering::Equal
253 } else {
254 self.acc = nagg;
255 Ordering::Greater
256 }
257 }
258 }More examples
crates/competitive/src/data_structure/splay_tree.rs (line 83)
78 fn bottom_up(mut node: BstDataMutRef<'_, Self>) {
79 let left = node
80 .reborrow()
81 .left()
82 .descend()
83 .map(|node| node.into_data().size)
84 .unwrap_or_default();
85 let right = node
86 .reborrow()
87 .right()
88 .descend()
89 .map(|node| node.into_data().size)
90 .unwrap_or_default();
91 node.data_mut().size = left + right + 1;
92 }
93
94 #[inline]
95 fn merge(
96 left: Option<SplayTreeRoot<K, V>>,
97 right: Option<SplayTreeRoot<K, V>>,
98 ) -> Option<SplayTreeRoot<K, V>> {
99 splay_operations::merge(left, right)
100 }
101
102 #[inline]
103 fn split<Seeker>(
104 node: Option<SplayTreeRoot<K, V>>,
105 seeker: Seeker,
106 equal_side: EqualSide,
107 ) -> (Option<SplayTreeRoot<K, V>>, Option<SplayTreeRoot<K, V>>)
108 where
109 Seeker: BstSeeker<Spec = Self>,
110 {
111 splay_operations::split(node, seeker, equal_side)
112 }
113}
114
115pub struct SplayTree<K, V, A = MemoryPool<SplayTreeNode<K, V>>>
116where
117 A: Allocator<SplayTreeNode<K, V>>,
118{
119 root: Option<SplayTreeRoot<K, V>>,
120 length: usize,
121 allocator: ManuallyDrop<A>,
122}
123
124impl<K, V, A> Debug for SplayTree<K, V, A>
125where
126 K: Debug,
127 V: Debug,
128 A: Allocator<SplayTreeNode<K, V>>,
129{
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 f.debug_struct("SplayTree")
132 .field("length", &self.length)
133 .finish_non_exhaustive()
134 }
135}
136
137impl<K, V, A> Default for SplayTree<K, V, A>
138where
139 A: Allocator<SplayTreeNode<K, V>> + Default,
140{
141 fn default() -> Self {
142 Self {
143 root: None,
144 length: 0,
145 allocator: ManuallyDrop::new(A::default()),
146 }
147 }
148}
149
150impl<K, V, A> Drop for SplayTree<K, V, A>
151where
152 A: Allocator<SplayTreeNode<K, V>>,
153{
154 fn drop(&mut self) {
155 unsafe {
156 if let Some(root) = self.root.take() {
157 root.into_dying().drop_all(self.allocator.deref_mut());
158 }
159 ManuallyDrop::drop(&mut self.allocator);
160 }
161 }
162}
163
164impl<K, V> SplayTree<K, V> {
165 pub fn new() -> Self {
166 Self::default()
167 }
168
169 pub fn with_capacity(capacity: usize) -> Self {
170 Self {
171 root: None,
172 length: 0,
173 allocator: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
174 }
175 }
176}
177
178impl<K, V, A> SplayTree<K, V, A>
179where
180 A: Allocator<SplayTreeNode<K, V>>,
181{
182 #[inline]
183 fn splay<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
184 where
185 Seeker: BstSeeker<Spec = SplayTreeSpec<K, V>>,
186 {
187 let (ordering, root) = splay_operations::splay(self.root.take()?, seeker);
188 self.root = Some(root);
189 Some(ordering)
190 }
191
192 fn splay_by_key<Q>(&mut self, key: &Q) -> Option<Ordering>
193 where
194 K: Borrow<Q>,
195 Q: Ord + ?Sized,
196 {
197 self.splay(SeekByKey::new(key))
198 }
199
200 fn splay_by_size(&mut self, index: usize) -> Option<Ordering> {
201 self.splay(SeekBySize::new(index))
202 }
203
204 pub fn get<Q>(&mut self, key: &Q) -> Option<&V>
205 where
206 K: Borrow<Q>,
207 Q: Ord + ?Sized,
208 {
209 self.get_key_value(key).map(|(_, value)| value)
210 }
211
212 pub fn get_key_value<Q>(&mut self, key: &Q) -> Option<(&K, &V)>
213 where
214 K: Borrow<Q>,
215 Q: Ord + ?Sized,
216 {
217 matches!(self.splay_by_key(key)?, Ordering::Equal).then(|| {
218 let data = self.root.as_ref().unwrap().reborrow().into_data();
219 (&data.key, &data.value)
220 })
221 }
222
223 pub fn get_key_value_at(&mut self, index: usize) -> Option<(&K, &V)> {
224 if index >= self.length {
225 return None;
226 }
227 self.splay_by_size(index);
228 let data = self.root.as_ref()?.reborrow().into_data();
229 Some((&data.key, &data.value))
230 }
231
232 pub fn insert(&mut self, key: K, value: V) -> Option<V>
233 where
234 K: Ord,
235 {
236 let ordering = self.splay_by_key(&key);
237 if matches!(ordering, Some(Ordering::Equal)) {
238 return Some(replace(
239 &mut self
240 .root
241 .as_mut()
242 .unwrap()
243 .borrow_datamut()
244 .data_mut()
245 .value,
246 value,
247 ));
248 }
249 let mut node = BstRoot::from_data(
250 SplayTreeData {
251 key,
252 value,
253 size: 1,
254 },
255 self.allocator.deref_mut(),
256 );
257 if let Some(mut root) = self.root.take() {
258 match ordering.unwrap() {
259 Ordering::Greater => {
260 let left = unsafe { root.borrow_mut().left_mut().take() };
261 if let Some(left) = left {
262 unsafe { node.borrow_mut().left_mut().set(left) };
263 }
264 SplayTreeSpec::bottom_up(root.borrow_datamut());
265 unsafe { node.borrow_mut().right_mut().set(root) };
266 }
267 Ordering::Less => {
268 let right = unsafe { root.borrow_mut().right_mut().take() };
269 if let Some(right) = right {
270 unsafe { node.borrow_mut().right_mut().set(right) };
271 }
272 SplayTreeSpec::bottom_up(root.borrow_datamut());
273 unsafe { node.borrow_mut().left_mut().set(root) };
274 }
275 Ordering::Equal => unreachable!(),
276 }
277 SplayTreeSpec::bottom_up(node.borrow_datamut());
278 }
279 self.root = Some(node);
280 self.length += 1;
281 None
282 }
283
284 pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
285 where
286 K: Borrow<Q>,
287 Q: Ord + ?Sized,
288 {
289 if !matches!(self.splay_by_key(key)?, Ordering::Equal) {
290 return None;
291 }
292 Some(self.remove_root().1)
293 }
294
295 pub fn remove_at(&mut self, index: usize) -> Option<(K, V)> {
296 if index >= self.length {
297 return None;
298 }
299 self.splay_by_size(index);
300 Some(self.remove_root())
301 }
302
303 fn remove_root(&mut self) -> (K, V) {
304 let mut node = self.root.take().unwrap();
305 let left = unsafe { node.borrow_mut().left_mut().take() };
306 let right = unsafe { node.borrow_mut().right_mut().take() };
307 self.root = SplayTreeSpec::merge(left, right);
308 self.length -= 1;
309 let data = unsafe { node.into_dying().into_data(self.allocator.deref_mut()) };
310 (data.key, data.value)
311 }
312
313 pub fn len(&self) -> usize {
314 self.length
315 }
316
317 pub fn is_empty(&self) -> bool {
318 self.length == 0
319 }
320
321 pub fn iter(&mut self) -> Iter<'_, K, V> {
322 Iter::new(Split3::seek_by_size(&mut self.root, ..))
323 }
324
325 pub fn range<Q, R>(&mut self, range: R) -> Iter<'_, K, V>
326 where
327 K: Borrow<Q>,
328 Q: Ord + ?Sized,
329 R: RangeBounds<Q>,
330 {
331 Iter::new(Split3::seek_by_key(&mut self.root, range))
332 }
333
334 pub fn range_at<R>(&mut self, range: R) -> Iter<'_, K, V>
335 where
336 R: RangeBounds<usize>,
337 {
338 Iter::new(Split3::seek_by_size(&mut self.root, range))
339 }
340}
341
342pub struct Iter<'a, K, V> {
343 split: Split3<'a, SplayTreeSpec<K, V>>,
344 front: Vec<NonNull<SplayTreeNode<K, V>>>,
345 back: Vec<NonNull<SplayTreeNode<K, V>>>,
346 remaining: usize,
347}
348
349impl<K, V> Debug for Iter<'_, K, V> {
350 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351 f.debug_struct("Iter")
352 .field("remaining", &self.remaining)
353 .finish_non_exhaustive()
354 }
355}
356
357impl<'a, K, V> Iter<'a, K, V> {
358 fn new(split: Split3<'a, SplayTreeSpec<K, V>>) -> Self {
359 let remaining = split
360 .mid()
361 .map(|node| node.into_data().size)
362 .unwrap_or_default();
363 let mut iter = Self {
364 split,
365 front: vec![],
366 back: vec![],
367 remaining,
368 };
369 if let Some(root) = iter.split.mid() {
370 Self::push_left(root.node, &mut iter.front);
371 Self::push_right(root.node, &mut iter.back);
372 }
373 iter
374 }crates/competitive/src/data_structure/implicit_splay_tree.rs (line 88)
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 }crates/competitive/src/data_structure/implicit_treap.rs (line 89)
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 }
463
464 pub fn partition_point_acc<F>(&mut self, left: usize, mut pred: F) -> usize
465 where
466 F: FnMut(&T::Agg) -> bool,
467 {
468 let mut split3 = Split3::seek_by_size(&mut self.root, left..);
469 let front_size = split3
470 .left()
471 .map(|node| node.into_data().size)
472 .unwrap_or_default();
473 let split = split3.split_mid(SeekByAccCond::new(|acc| !pred(acc)), EqualSide::Right);
474 let index = split
475 .left()
476 .map(|node| node.into_data().size)
477 .unwrap_or_default();
478 front_size + index
479 }
480
481 pub fn rpartition_point_acc<F>(&mut self, right: usize, mut pred: F) -> usize
482 where
483 F: FnMut(&T::Agg) -> bool,
484 {
485 let mut split3 = Split3::seek_by_size(&mut self.root, ..right);
486 let split = split3.split_mid(SeekByRaccCond::new(|acc| !pred(acc)), EqualSide::Left);
487 split
488 .left()
489 .map(|node| node.into_data().size)
490 .unwrap_or_default()
491 }crates/competitive/src/data_structure/binary_search_tree/data.rs (line 44)
40 pub fn bottom_up<Spec>(mut node: BstDataMutRef<'_, Spec>)
41 where
42 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAgg, Value = Self>>,
43 {
44 let mut agg = node.reborrow().into_data().bst_data().agg.clone();
45 if let Ok(left) = node.reborrow().left().descend() {
46 agg = M::operate(&left.into_data().bst_data().agg, &agg);
47 }
48 if let Ok(right) = node.reborrow().right().descend() {
49 agg = M::operate(&agg, &right.into_data().bst_data().agg);
50 }
51 node.data_mut().bst_data_mut().agg = agg;
52 }
53}
54
55pub struct MonoidActElement<M>
56where
57 M: MonoidAct,
58{
59 pub key: M::Key,
60 pub act: M::Act,
61}
62
63impl<M> Debug for MonoidActElement<M>
64where
65 M: MonoidAct<Key: Debug, Act: Debug>,
66{
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.debug_struct("MonoidActElement")
69 .field("key", &self.key)
70 .field("act", &self.act)
71 .finish()
72 }
73}
74
75impl<M> MonoidActElement<M>
76where
77 M: MonoidAct,
78{
79 pub fn from_key(key: M::Key) -> Self {
80 Self {
81 key,
82 act: M::unit(),
83 }
84 }
85
86 pub fn update_act<Spec>(mut node: BstDataMutRef<'_, Spec>, act: &M::Act)
87 where
88 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAct, Value = Self>>,
89 {
90 M::operate_assign(&mut node.data_mut().bst_data_mut().act, act);
91 M::act_assign(&mut node.data_mut().bst_data_mut().key, act);
92 }
93
94 pub fn top_down<Spec>(mut node: BstDataMutRef<'_, Spec>)
95 where
96 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAct, Value = Self>>,
97 {
98 let act = replace(&mut node.data_mut().bst_data_mut().act, M::unit());
99 if let Ok(left) = node.reborrow_datamut().left().descend() {
100 Self::update_act(left, &act);
101 }
102 if let Ok(right) = node.reborrow_datamut().right().descend() {
103 Self::update_act(right, &act);
104 }
105 }
106}
107
108pub struct LazyMapElement<L>
109where
110 L: LazyMapMonoid,
111{
112 pub key: L::Key,
113 pub agg: L::Agg,
114 pub act: L::Act,
115}
116
117impl<L> Debug for LazyMapElement<L>
118where
119 L: LazyMapMonoid<Key: Debug, Agg: Debug, Act: Debug>,
120{
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.debug_struct("LazyMapElement")
123 .field("key", &self.key)
124 .field("agg", &self.agg)
125 .field("act", &self.act)
126 .finish()
127 }
128}
129
130impl<L> LazyMapElement<L>
131where
132 L: LazyMapMonoid,
133{
134 pub fn from_key(key: L::Key) -> Self {
135 let agg = L::single_agg(&key);
136 Self {
137 key,
138 agg,
139 act: L::act_unit(),
140 }
141 }
142
143 pub fn update_act<Spec>(mut node: BstDataMutRef<'_, Spec>, act: &L::Act)
144 where
145 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
146 {
147 if L::is_act_unit(act) {
148 return;
149 }
150 L::act_operate_assign(&mut node.data_mut().bst_data_mut().act, act);
151 node.data_mut().bst_data_mut().key =
152 L::act_key(&node.reborrow().into_data().bst_data().key, act);
153 if let Some(nxlazy) = L::act_agg(&node.reborrow().into_data().bst_data().agg, act) {
154 node.data_mut().bst_data_mut().agg = nxlazy;
155 } else {
156 Self::top_down(node.reborrow_datamut());
157 Self::bottom_up(node.reborrow_datamut());
158 }
159 }
160
161 pub fn top_down<Spec>(mut node: BstDataMutRef<'_, Spec>)
162 where
163 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
164 {
165 if L::is_act_unit(&node.reborrow().into_data().bst_data().act) {
166 return;
167 }
168 let act = replace(&mut node.data_mut().bst_data_mut().act, L::act_unit());
169 if let Ok(left) = node.reborrow_datamut().left().descend() {
170 Self::update_act(left, &act);
171 }
172 if let Ok(right) = node.reborrow_datamut().right().descend() {
173 Self::update_act(right, &act);
174 }
175 }
176
177 pub fn bottom_up<Spec>(mut node: BstDataMutRef<'_, Spec>)
178 where
179 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
180 {
181 let mut agg = L::single_agg(&node.reborrow().into_data().bst_data().key);
182 if let Ok(left) = node.reborrow().left().descend() {
183 agg = L::agg_operate(&left.into_data().bst_data().agg, &agg);
184 }
185 if let Ok(right) = node.reborrow().right().descend() {
186 agg = L::agg_operate(&agg, &right.into_data().bst_data().agg);
187 }
188 node.data_mut().bst_data_mut().agg = agg;
189 }crates/competitive/src/tree/link_cut_tree.rs (line 101)
99 fn top_down(mut node: BstDataMutRef<'_, Self>) {
100 let pointer = node.node;
101 if node.reborrow().into_data().index_and_reverse & 1 != 0 {
102 node.data_mut().index_and_reverse &= !1;
103 let children = unsafe { pointer.as_ref().child };
104 for child in children.into_iter().flatten() {
105 unsafe { Self::toggle(child) };
106 }
107 }
108 let children = unsafe { pointer.as_ref().child };
109 let data = unsafe { &mut (*pointer.as_ptr()).data.inner };
110 let children =
111 children.map(|child| child.map(|child| unsafe { &mut (*child.as_ptr()).data.inner }));
112 S::top_down(data, children);
113 }Additional examples can be found in:
Sourcepub fn traverse<F>(self, f: &mut F)where
F: FnMut(Self),
pub fn traverse<F>(self, f: &mut F)where
F: FnMut(Self),
Examples found in repository?
crates/competitive/src/data_structure/binary_search_tree/node.rs (line 379)
374 pub fn traverse<F>(self, f: &mut F)
375 where
376 F: FnMut(Self),
377 {
378 if let Ok(left) = self.left().descend() {
379 left.traverse(f);
380 }
381 f(self);
382 if let Ok(right) = self.right().descend() {
383 right.traverse(f);
384 }
385 }Sourcepub fn leftmost(self) -> Self
pub fn leftmost(self) -> Self
Examples found in repository?
crates/competitive/src/data_structure/treap.rs (line 422)
412 pub fn find_by_key<Q>(&mut self, key: &Q) -> Option<BstNodeId<TreapSpec<M, L>>>
413 where
414 M: MonoidAct<Key: Borrow<Q>>,
415 Q: Ord + ?Sized,
416 {
417 let split = Split::new(
418 &mut self.root,
419 SeekByKey::<TreapSpec<M, L>, M::Key, Q>::new(key),
420 EqualSide::Right,
421 );
422 let node = split.right()?.leftmost();
423 matches!(node.into_data().key.key.borrow().cmp(key), Ordering::Equal)
424 .then(|| self.node_id_manager.registered_node_id(node))
425 .flatten()
426 }
427
428 pub fn find_by_acc_cond<F>(&mut self, f: F) -> Option<BstNodeId<TreapSpec<M, L>>>
429 where
430 F: FnMut(&L::Agg) -> bool,
431 {
432 let split = Split::new(
433 &mut self.root,
434 SeekByAccCond::<TreapSpec<M, L>, L, F>::new(f),
435 EqualSide::Right,
436 );
437 let node = split.right()?.leftmost();
438 self.node_id_manager.registered_node_id(node)
439 }Sourcepub fn rightmost(self) -> Self
pub fn rightmost(self) -> Self
Examples found in repository?
crates/competitive/src/data_structure/treap.rs (line 450)
441 pub fn find_by_racc_cond<F>(&mut self, f: F) -> Option<BstNodeId<TreapSpec<M, L>>>
442 where
443 F: FnMut(&L::Agg) -> bool,
444 {
445 let split = Split::new(
446 &mut self.root,
447 SeekByRaccCond::<TreapSpec<M, L>, L, F>::new(f),
448 EqualSide::Left,
449 );
450 let node = split.left()?.rightmost();
451 self.node_id_manager.registered_node_id(node)
452 }Source§impl<'a, Spec> BstNodeRef<DataMut<'a>, Spec>where
Spec: BstSpec,
impl<'a, Spec> BstNodeRef<DataMut<'a>, Spec>where
Spec: BstSpec,
Sourcepub fn reborrow_datamut(&mut self) -> BstNodeRef<DataMut<'_>, Spec>
pub fn reborrow_datamut(&mut self) -> BstNodeRef<DataMut<'_>, Spec>
Examples found in repository?
More examples
crates/competitive/src/data_structure/binary_search_tree/data.rs (line 99)
94 pub fn top_down<Spec>(mut node: BstDataMutRef<'_, Spec>)
95 where
96 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAct, Value = Self>>,
97 {
98 let act = replace(&mut node.data_mut().bst_data_mut().act, M::unit());
99 if let Ok(left) = node.reborrow_datamut().left().descend() {
100 Self::update_act(left, &act);
101 }
102 if let Ok(right) = node.reborrow_datamut().right().descend() {
103 Self::update_act(right, &act);
104 }
105 }
106}
107
108pub struct LazyMapElement<L>
109where
110 L: LazyMapMonoid,
111{
112 pub key: L::Key,
113 pub agg: L::Agg,
114 pub act: L::Act,
115}
116
117impl<L> Debug for LazyMapElement<L>
118where
119 L: LazyMapMonoid<Key: Debug, Agg: Debug, Act: Debug>,
120{
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.debug_struct("LazyMapElement")
123 .field("key", &self.key)
124 .field("agg", &self.agg)
125 .field("act", &self.act)
126 .finish()
127 }
128}
129
130impl<L> LazyMapElement<L>
131where
132 L: LazyMapMonoid,
133{
134 pub fn from_key(key: L::Key) -> Self {
135 let agg = L::single_agg(&key);
136 Self {
137 key,
138 agg,
139 act: L::act_unit(),
140 }
141 }
142
143 pub fn update_act<Spec>(mut node: BstDataMutRef<'_, Spec>, act: &L::Act)
144 where
145 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
146 {
147 if L::is_act_unit(act) {
148 return;
149 }
150 L::act_operate_assign(&mut node.data_mut().bst_data_mut().act, act);
151 node.data_mut().bst_data_mut().key =
152 L::act_key(&node.reborrow().into_data().bst_data().key, act);
153 if let Some(nxlazy) = L::act_agg(&node.reborrow().into_data().bst_data().agg, act) {
154 node.data_mut().bst_data_mut().agg = nxlazy;
155 } else {
156 Self::top_down(node.reborrow_datamut());
157 Self::bottom_up(node.reborrow_datamut());
158 }
159 }
160
161 pub fn top_down<Spec>(mut node: BstDataMutRef<'_, Spec>)
162 where
163 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
164 {
165 if L::is_act_unit(&node.reborrow().into_data().bst_data().act) {
166 return;
167 }
168 let act = replace(&mut node.data_mut().bst_data_mut().act, L::act_unit());
169 if let Ok(left) = node.reborrow_datamut().left().descend() {
170 Self::update_act(left, &act);
171 }
172 if let Ok(right) = node.reborrow_datamut().right().descend() {
173 Self::update_act(right, &act);
174 }
175 }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 }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 }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 }
156
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 }Sourcepub fn data_mut(&mut self) -> &mut Spec::Data
pub fn data_mut(&mut self) -> &mut Spec::Data
Examples found in repository?
crates/competitive/src/data_structure/splay_tree.rs (line 91)
78 fn bottom_up(mut node: BstDataMutRef<'_, Self>) {
79 let left = node
80 .reborrow()
81 .left()
82 .descend()
83 .map(|node| node.into_data().size)
84 .unwrap_or_default();
85 let right = node
86 .reborrow()
87 .right()
88 .descend()
89 .map(|node| node.into_data().size)
90 .unwrap_or_default();
91 node.data_mut().size = left + right + 1;
92 }
93
94 #[inline]
95 fn merge(
96 left: Option<SplayTreeRoot<K, V>>,
97 right: Option<SplayTreeRoot<K, V>>,
98 ) -> Option<SplayTreeRoot<K, V>> {
99 splay_operations::merge(left, right)
100 }
101
102 #[inline]
103 fn split<Seeker>(
104 node: Option<SplayTreeRoot<K, V>>,
105 seeker: Seeker,
106 equal_side: EqualSide,
107 ) -> (Option<SplayTreeRoot<K, V>>, Option<SplayTreeRoot<K, V>>)
108 where
109 Seeker: BstSeeker<Spec = Self>,
110 {
111 splay_operations::split(node, seeker, equal_side)
112 }
113}
114
115pub struct SplayTree<K, V, A = MemoryPool<SplayTreeNode<K, V>>>
116where
117 A: Allocator<SplayTreeNode<K, V>>,
118{
119 root: Option<SplayTreeRoot<K, V>>,
120 length: usize,
121 allocator: ManuallyDrop<A>,
122}
123
124impl<K, V, A> Debug for SplayTree<K, V, A>
125where
126 K: Debug,
127 V: Debug,
128 A: Allocator<SplayTreeNode<K, V>>,
129{
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 f.debug_struct("SplayTree")
132 .field("length", &self.length)
133 .finish_non_exhaustive()
134 }
135}
136
137impl<K, V, A> Default for SplayTree<K, V, A>
138where
139 A: Allocator<SplayTreeNode<K, V>> + Default,
140{
141 fn default() -> Self {
142 Self {
143 root: None,
144 length: 0,
145 allocator: ManuallyDrop::new(A::default()),
146 }
147 }
148}
149
150impl<K, V, A> Drop for SplayTree<K, V, A>
151where
152 A: Allocator<SplayTreeNode<K, V>>,
153{
154 fn drop(&mut self) {
155 unsafe {
156 if let Some(root) = self.root.take() {
157 root.into_dying().drop_all(self.allocator.deref_mut());
158 }
159 ManuallyDrop::drop(&mut self.allocator);
160 }
161 }
162}
163
164impl<K, V> SplayTree<K, V> {
165 pub fn new() -> Self {
166 Self::default()
167 }
168
169 pub fn with_capacity(capacity: usize) -> Self {
170 Self {
171 root: None,
172 length: 0,
173 allocator: ManuallyDrop::new(MemoryPool::with_capacity(capacity)),
174 }
175 }
176}
177
178impl<K, V, A> SplayTree<K, V, A>
179where
180 A: Allocator<SplayTreeNode<K, V>>,
181{
182 #[inline]
183 fn splay<Seeker>(&mut self, seeker: Seeker) -> Option<Ordering>
184 where
185 Seeker: BstSeeker<Spec = SplayTreeSpec<K, V>>,
186 {
187 let (ordering, root) = splay_operations::splay(self.root.take()?, seeker);
188 self.root = Some(root);
189 Some(ordering)
190 }
191
192 fn splay_by_key<Q>(&mut self, key: &Q) -> Option<Ordering>
193 where
194 K: Borrow<Q>,
195 Q: Ord + ?Sized,
196 {
197 self.splay(SeekByKey::new(key))
198 }
199
200 fn splay_by_size(&mut self, index: usize) -> Option<Ordering> {
201 self.splay(SeekBySize::new(index))
202 }
203
204 pub fn get<Q>(&mut self, key: &Q) -> Option<&V>
205 where
206 K: Borrow<Q>,
207 Q: Ord + ?Sized,
208 {
209 self.get_key_value(key).map(|(_, value)| value)
210 }
211
212 pub fn get_key_value<Q>(&mut self, key: &Q) -> Option<(&K, &V)>
213 where
214 K: Borrow<Q>,
215 Q: Ord + ?Sized,
216 {
217 matches!(self.splay_by_key(key)?, Ordering::Equal).then(|| {
218 let data = self.root.as_ref().unwrap().reborrow().into_data();
219 (&data.key, &data.value)
220 })
221 }
222
223 pub fn get_key_value_at(&mut self, index: usize) -> Option<(&K, &V)> {
224 if index >= self.length {
225 return None;
226 }
227 self.splay_by_size(index);
228 let data = self.root.as_ref()?.reborrow().into_data();
229 Some((&data.key, &data.value))
230 }
231
232 pub fn insert(&mut self, key: K, value: V) -> Option<V>
233 where
234 K: Ord,
235 {
236 let ordering = self.splay_by_key(&key);
237 if matches!(ordering, Some(Ordering::Equal)) {
238 return Some(replace(
239 &mut self
240 .root
241 .as_mut()
242 .unwrap()
243 .borrow_datamut()
244 .data_mut()
245 .value,
246 value,
247 ));
248 }
249 let mut node = BstRoot::from_data(
250 SplayTreeData {
251 key,
252 value,
253 size: 1,
254 },
255 self.allocator.deref_mut(),
256 );
257 if let Some(mut root) = self.root.take() {
258 match ordering.unwrap() {
259 Ordering::Greater => {
260 let left = unsafe { root.borrow_mut().left_mut().take() };
261 if let Some(left) = left {
262 unsafe { node.borrow_mut().left_mut().set(left) };
263 }
264 SplayTreeSpec::bottom_up(root.borrow_datamut());
265 unsafe { node.borrow_mut().right_mut().set(root) };
266 }
267 Ordering::Less => {
268 let right = unsafe { root.borrow_mut().right_mut().take() };
269 if let Some(right) = right {
270 unsafe { node.borrow_mut().right_mut().set(right) };
271 }
272 SplayTreeSpec::bottom_up(root.borrow_datamut());
273 unsafe { node.borrow_mut().left_mut().set(root) };
274 }
275 Ordering::Equal => unreachable!(),
276 }
277 SplayTreeSpec::bottom_up(node.borrow_datamut());
278 }
279 self.root = Some(node);
280 self.length += 1;
281 None
282 }More examples
crates/competitive/src/data_structure/implicit_splay_tree.rs (line 87)
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 }crates/competitive/src/data_structure/implicit_treap.rs (line 88)
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/binary_search_tree/data.rs (line 51)
40 pub fn bottom_up<Spec>(mut node: BstDataMutRef<'_, Spec>)
41 where
42 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAgg, Value = Self>>,
43 {
44 let mut agg = node.reborrow().into_data().bst_data().agg.clone();
45 if let Ok(left) = node.reborrow().left().descend() {
46 agg = M::operate(&left.into_data().bst_data().agg, &agg);
47 }
48 if let Ok(right) = node.reborrow().right().descend() {
49 agg = M::operate(&agg, &right.into_data().bst_data().agg);
50 }
51 node.data_mut().bst_data_mut().agg = agg;
52 }
53}
54
55pub struct MonoidActElement<M>
56where
57 M: MonoidAct,
58{
59 pub key: M::Key,
60 pub act: M::Act,
61}
62
63impl<M> Debug for MonoidActElement<M>
64where
65 M: MonoidAct<Key: Debug, Act: Debug>,
66{
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.debug_struct("MonoidActElement")
69 .field("key", &self.key)
70 .field("act", &self.act)
71 .finish()
72 }
73}
74
75impl<M> MonoidActElement<M>
76where
77 M: MonoidAct,
78{
79 pub fn from_key(key: M::Key) -> Self {
80 Self {
81 key,
82 act: M::unit(),
83 }
84 }
85
86 pub fn update_act<Spec>(mut node: BstDataMutRef<'_, Spec>, act: &M::Act)
87 where
88 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAct, Value = Self>>,
89 {
90 M::operate_assign(&mut node.data_mut().bst_data_mut().act, act);
91 M::act_assign(&mut node.data_mut().bst_data_mut().key, act);
92 }
93
94 pub fn top_down<Spec>(mut node: BstDataMutRef<'_, Spec>)
95 where
96 Spec: BstSpec<Data: BstDataAccess<marker::MonoidAct, Value = Self>>,
97 {
98 let act = replace(&mut node.data_mut().bst_data_mut().act, M::unit());
99 if let Ok(left) = node.reborrow_datamut().left().descend() {
100 Self::update_act(left, &act);
101 }
102 if let Ok(right) = node.reborrow_datamut().right().descend() {
103 Self::update_act(right, &act);
104 }
105 }
106}
107
108pub struct LazyMapElement<L>
109where
110 L: LazyMapMonoid,
111{
112 pub key: L::Key,
113 pub agg: L::Agg,
114 pub act: L::Act,
115}
116
117impl<L> Debug for LazyMapElement<L>
118where
119 L: LazyMapMonoid<Key: Debug, Agg: Debug, Act: Debug>,
120{
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.debug_struct("LazyMapElement")
123 .field("key", &self.key)
124 .field("agg", &self.agg)
125 .field("act", &self.act)
126 .finish()
127 }
128}
129
130impl<L> LazyMapElement<L>
131where
132 L: LazyMapMonoid,
133{
134 pub fn from_key(key: L::Key) -> Self {
135 let agg = L::single_agg(&key);
136 Self {
137 key,
138 agg,
139 act: L::act_unit(),
140 }
141 }
142
143 pub fn update_act<Spec>(mut node: BstDataMutRef<'_, Spec>, act: &L::Act)
144 where
145 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
146 {
147 if L::is_act_unit(act) {
148 return;
149 }
150 L::act_operate_assign(&mut node.data_mut().bst_data_mut().act, act);
151 node.data_mut().bst_data_mut().key =
152 L::act_key(&node.reborrow().into_data().bst_data().key, act);
153 if let Some(nxlazy) = L::act_agg(&node.reborrow().into_data().bst_data().agg, act) {
154 node.data_mut().bst_data_mut().agg = nxlazy;
155 } else {
156 Self::top_down(node.reborrow_datamut());
157 Self::bottom_up(node.reborrow_datamut());
158 }
159 }
160
161 pub fn top_down<Spec>(mut node: BstDataMutRef<'_, Spec>)
162 where
163 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
164 {
165 if L::is_act_unit(&node.reborrow().into_data().bst_data().act) {
166 return;
167 }
168 let act = replace(&mut node.data_mut().bst_data_mut().act, L::act_unit());
169 if let Ok(left) = node.reborrow_datamut().left().descend() {
170 Self::update_act(left, &act);
171 }
172 if let Ok(right) = node.reborrow_datamut().right().descend() {
173 Self::update_act(right, &act);
174 }
175 }
176
177 pub fn bottom_up<Spec>(mut node: BstDataMutRef<'_, Spec>)
178 where
179 Spec: BstSpec<Data: BstDataAccess<marker::LazyMap, Value = Self>>,
180 {
181 let mut agg = L::single_agg(&node.reborrow().into_data().bst_data().key);
182 if let Ok(left) = node.reborrow().left().descend() {
183 agg = L::agg_operate(&left.into_data().bst_data().agg, &agg);
184 }
185 if let Ok(right) = node.reborrow().right().descend() {
186 agg = L::agg_operate(&agg, &right.into_data().bst_data().agg);
187 }
188 node.data_mut().bst_data_mut().agg = agg;
189 }crates/competitive/src/tree/link_cut_tree.rs (line 102)
99 fn top_down(mut node: BstDataMutRef<'_, Self>) {
100 let pointer = node.node;
101 if node.reborrow().into_data().index_and_reverse & 1 != 0 {
102 node.data_mut().index_and_reverse &= !1;
103 let children = unsafe { pointer.as_ref().child };
104 for child in children.into_iter().flatten() {
105 unsafe { Self::toggle(child) };
106 }
107 }
108 let children = unsafe { pointer.as_ref().child };
109 let data = unsafe { &mut (*pointer.as_ptr()).data.inner };
110 let children =
111 children.map(|child| child.map(|child| unsafe { &mut (*child.as_ptr()).data.inner }));
112 S::top_down(data, children);
113 }crates/competitive/src/tree/top_tree.rs (line 160)
157 fn top_down(mut node: BstDataMutRef<'_, Self>) {
158 let pointer = node.node;
159 if node.reborrow().into_data().index_and_reverse & 1 != 0 {
160 node.data_mut().index_and_reverse &= !1;
161 for child in unsafe { pointer.as_ref().child }.into_iter().flatten() {
162 unsafe { Self::toggle(child) };
163 }
164 }
165
166 if !Self::is_unit(&node.reborrow().into_data().heavy_action) {
167 let action = replace(
168 &mut node.data_mut().heavy_action,
169 <A::ActionMonoid as Unital>::unit(),
170 );
171 for child in unsafe { pointer.as_ref().child }.into_iter().flatten() {
172 unsafe { Self::apply_heavy(child, &action) };
173 }
174 }
175 if !Self::is_unit(&node.reborrow().into_data().light_action) {
176 let action = replace(
177 &mut node.data_mut().light_action,
178 <A::ActionMonoid as Unital>::unit(),
179 );
180 for child in unsafe { pointer.as_ref().child }.into_iter().flatten() {
181 unsafe { Self::apply_light(child, &action) };
182 }
183 if let Some(light) = node.reborrow().into_data().light {
184 unsafe { RakeBstSpec::<S, A>::apply(light, &action) };
185 }
186 }
187 }
188
189 #[inline]
190 fn bottom_up(node: BstDataMutRef<'_, Self>) {
191 let pointer = node.node;
192 let data = unsafe { &mut (*pointer.as_ptr()).data };
193 let mut sum = if let Some(light) = data.light {
194 S::add_vertex(unsafe { &light.as_ref().data.sum }, &data.info)
195 } else {
196 S::vertex(&data.info)
197 };
198 if let Some(left) = unsafe { pointer.as_ref().child[0] } {
199 sum = S::compress(unsafe { &left.as_ref().data.sum }, &sum);
200 }
201 if let Some(right) = unsafe { pointer.as_ref().child[1] } {
202 sum = S::compress(&sum, unsafe { &right.as_ref().data.sum });
203 }
204 data.sum = sum;
205 }
206
207 fn merge(_left: Option<BstRoot<Self>>, _right: Option<BstRoot<Self>>) -> Option<BstRoot<Self>> {
208 unreachable!("top trees do not merge auxiliary trees through BstSpec")
209 }
210
211 fn split<Seeker>(
212 _node: Option<BstRoot<Self>>,
213 _seeker: Seeker,
214 _equal_side: EqualSide,
215 ) -> (Option<BstRoot<Self>>, Option<BstRoot<Self>>)
216 where
217 Seeker: BstSeeker<Spec = Self>,
218 {
219 unreachable!("top trees do not split auxiliary trees through BstSpec")
220 }
221}
222
223impl<S, A> RakeBstSpec<S, A>
224where
225 S: TopTreeSpec,
226 A: TopTreeAction<S>,
227{
228 #[inline]
229 unsafe fn apply(mut node: RakePtr<S, A>, action: &A::Action) {
230 let data = unsafe { &mut node.as_mut().data };
231 A::act_point(&mut data.key, action);
232 A::act_point(&mut data.sum, action);
233 TopBstSpec::<S, A>::compose(&mut data.action, action);
234 TopBstSpec::<S, A>::compose(&mut data.buffer, action);
235 }
236}
237
238impl<S, A> BstSpec for RakeBstSpec<S, A>
239where
240 S: TopTreeSpec,
241 A: TopTreeAction<S>,
242{
243 type Parent = WithParent<Self::Data>;
244 type Data = RakeData<S, A>;
245
246 #[inline]
247 fn top_down(mut node: BstDataMutRef<'_, Self>) {
248 if TopBstSpec::<S, A>::is_unit(&node.reborrow().into_data().action) {
249 return;
250 }
251 let pointer = node.node;
252 let action = replace(
253 &mut node.data_mut().action,
254 <A::ActionMonoid as Unital>::unit(),
255 );
256 for child in unsafe { pointer.as_ref().child }.into_iter().flatten() {
257 unsafe { Self::apply(child, &action) };
258 }
259 }Sourcepub fn swap_children(&mut self)
pub fn swap_children(&mut self)
Examples found in repository?
More examples
Source§impl<'a, Spec> BstNodeRef<DataMut<'a>, Spec>where
Spec: BstSpec<Parent: 'a, Data: 'a>,
impl<'a, Spec> BstNodeRef<DataMut<'a>, Spec>where
Spec: BstSpec<Parent: 'a, Data: 'a>,
Sourcepub fn into_data_mut(self) -> &'a mut Spec::Data
pub fn into_data_mut(self) -> &'a mut Spec::Data
Examples found in repository?
crates/competitive/src/data_structure/treap.rs (line 333)
321 pub fn change(
322 &mut self,
323 node_id: BstNodeId<TreapSpec<M, L>>,
324 f: impl FnOnce(&mut L::Key),
325 ) -> bool {
326 if !self.node_id_manager.contains(&node_id) {
327 return false;
328 }
329 unsafe {
330 WithParent::resolve_top_down::<TreapSpec<M, L>>(
331 node_id.reborrow_datamut(&mut self.root),
332 );
333 let data = node_id.reborrow_datamut(&mut self.root).into_data_mut();
334 f(&mut data.value.key);
335 WithParent::resolve_bottom_up::<TreapSpec<M, L>>(
336 node_id.reborrow_datamut(&mut self.root),
337 );
338 }
339 true
340 }
341
342 pub fn change_key_value(
343 &mut self,
344 node_id: BstNodeId<TreapSpec<M, L>>,
345 f: impl FnOnce(&mut M::Key, &mut L::Key),
346 ) -> bool {
347 if !self.node_id_manager.contains(&node_id) {
348 return false;
349 }
350 unsafe {
351 WithParent::resolve_top_down::<TreapSpec<M, L>>(
352 node_id.reborrow_datamut(&mut self.root),
353 );
354 let mut node = if WithParent::is_root(node_id.reborrow(&self.root)) {
355 WithParent::remove_root(&mut self.root).unwrap_unchecked()
356 } else {
357 WithParent::remove_not_root(node_id.reborrow_mut(&mut self.root))
358 };
359 let data = node.borrow_datamut().into_data_mut();
360 f(&mut data.key.key, &mut data.value.key);
361 self.root = TreapSpec::merge_ordered(self.root.take(), Some(node));
362 true
363 }
364 }Source§impl<'a, Spec> BstNodeRef<Mut<'a>, Spec>where
Spec: BstSpec,
impl<'a, Spec> BstNodeRef<Mut<'a>, Spec>where
Spec: BstSpec,
Sourcepub fn reborrow_datamut(&mut self) -> BstNodeRef<DataMut<'_>, Spec>
pub fn reborrow_datamut(&mut self) -> BstNodeRef<DataMut<'_>, Spec>
Examples found in repository?
crates/competitive/src/data_structure/binary_search_tree/node.rs (line 217)
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 }Sourcepub fn left_mut(&mut self) -> BstEdgeHandle<BstNodeRef<Mut<'_>, Spec>, Left>
pub fn left_mut(&mut self) -> BstEdgeHandle<BstNodeRef<Mut<'_>, Spec>, Left>
Examples found in repository?
crates/competitive/src/data_structure/binary_search_tree/node.rs (line 185)
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 }More examples
crates/competitive/src/data_structure/implicit_splay_tree.rs (line 327)
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/splay_tree.rs (line 260)
232 pub fn insert(&mut self, key: K, value: V) -> Option<V>
233 where
234 K: Ord,
235 {
236 let ordering = self.splay_by_key(&key);
237 if matches!(ordering, Some(Ordering::Equal)) {
238 return Some(replace(
239 &mut self
240 .root
241 .as_mut()
242 .unwrap()
243 .borrow_datamut()
244 .data_mut()
245 .value,
246 value,
247 ));
248 }
249 let mut node = BstRoot::from_data(
250 SplayTreeData {
251 key,
252 value,
253 size: 1,
254 },
255 self.allocator.deref_mut(),
256 );
257 if let Some(mut root) = self.root.take() {
258 match ordering.unwrap() {
259 Ordering::Greater => {
260 let left = unsafe { root.borrow_mut().left_mut().take() };
261 if let Some(left) = left {
262 unsafe { node.borrow_mut().left_mut().set(left) };
263 }
264 SplayTreeSpec::bottom_up(root.borrow_datamut());
265 unsafe { node.borrow_mut().right_mut().set(root) };
266 }
267 Ordering::Less => {
268 let right = unsafe { root.borrow_mut().right_mut().take() };
269 if let Some(right) = right {
270 unsafe { node.borrow_mut().right_mut().set(right) };
271 }
272 SplayTreeSpec::bottom_up(root.borrow_datamut());
273 unsafe { node.borrow_mut().left_mut().set(root) };
274 }
275 Ordering::Equal => unreachable!(),
276 }
277 SplayTreeSpec::bottom_up(node.borrow_datamut());
278 }
279 self.root = Some(node);
280 self.length += 1;
281 None
282 }
283
284 pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
285 where
286 K: Borrow<Q>,
287 Q: Ord + ?Sized,
288 {
289 if !matches!(self.splay_by_key(key)?, Ordering::Equal) {
290 return None;
291 }
292 Some(self.remove_root().1)
293 }
294
295 pub fn remove_at(&mut self, index: usize) -> Option<(K, V)> {
296 if index >= self.length {
297 return None;
298 }
299 self.splay_by_size(index);
300 Some(self.remove_root())
301 }
302
303 fn remove_root(&mut self) -> (K, V) {
304 let mut node = self.root.take().unwrap();
305 let left = unsafe { node.borrow_mut().left_mut().take() };
306 let right = unsafe { node.borrow_mut().right_mut().take() };
307 self.root = SplayTreeSpec::merge(left, right);
308 self.length -= 1;
309 let data = unsafe { node.into_dying().into_data(self.allocator.deref_mut()) };
310 (data.key, data.value)
311 }crates/competitive/src/data_structure/splay_operations.rs (line 279)
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}Sourcepub fn right_mut(&mut self) -> BstEdgeHandle<BstNodeRef<Mut<'_>, Spec>, Right>
pub fn right_mut(&mut self) -> BstEdgeHandle<BstNodeRef<Mut<'_>, Spec>, Right>
Examples found in repository?
crates/competitive/src/data_structure/binary_search_tree/node.rs (line 186)
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 }More examples
crates/competitive/src/data_structure/implicit_splay_tree.rs (line 338)
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/splay_tree.rs (line 265)
232 pub fn insert(&mut self, key: K, value: V) -> Option<V>
233 where
234 K: Ord,
235 {
236 let ordering = self.splay_by_key(&key);
237 if matches!(ordering, Some(Ordering::Equal)) {
238 return Some(replace(
239 &mut self
240 .root
241 .as_mut()
242 .unwrap()
243 .borrow_datamut()
244 .data_mut()
245 .value,
246 value,
247 ));
248 }
249 let mut node = BstRoot::from_data(
250 SplayTreeData {
251 key,
252 value,
253 size: 1,
254 },
255 self.allocator.deref_mut(),
256 );
257 if let Some(mut root) = self.root.take() {
258 match ordering.unwrap() {
259 Ordering::Greater => {
260 let left = unsafe { root.borrow_mut().left_mut().take() };
261 if let Some(left) = left {
262 unsafe { node.borrow_mut().left_mut().set(left) };
263 }
264 SplayTreeSpec::bottom_up(root.borrow_datamut());
265 unsafe { node.borrow_mut().right_mut().set(root) };
266 }
267 Ordering::Less => {
268 let right = unsafe { root.borrow_mut().right_mut().take() };
269 if let Some(right) = right {
270 unsafe { node.borrow_mut().right_mut().set(right) };
271 }
272 SplayTreeSpec::bottom_up(root.borrow_datamut());
273 unsafe { node.borrow_mut().left_mut().set(root) };
274 }
275 Ordering::Equal => unreachable!(),
276 }
277 SplayTreeSpec::bottom_up(node.borrow_datamut());
278 }
279 self.root = Some(node);
280 self.length += 1;
281 None
282 }
283
284 pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
285 where
286 K: Borrow<Q>,
287 Q: Ord + ?Sized,
288 {
289 if !matches!(self.splay_by_key(key)?, Ordering::Equal) {
290 return None;
291 }
292 Some(self.remove_root().1)
293 }
294
295 pub fn remove_at(&mut self, index: usize) -> Option<(K, V)> {
296 if index >= self.length {
297 return None;
298 }
299 self.splay_by_size(index);
300 Some(self.remove_root())
301 }
302
303 fn remove_root(&mut self) -> (K, V) {
304 let mut node = self.root.take().unwrap();
305 let left = unsafe { node.borrow_mut().left_mut().take() };
306 let right = unsafe { node.borrow_mut().right_mut().take() };
307 self.root = SplayTreeSpec::merge(left, right);
308 self.length -= 1;
309 let data = unsafe { node.into_dying().into_data(self.allocator.deref_mut()) };
310 (data.key, data.value)
311 }crates/competitive/src/data_structure/splay_operations.rs (line 293)
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}Source§impl<'a, Spec> BstNodeRef<Mut<'a>, Spec>where
Spec: BstSpec<Data: 'a>,
impl<'a, Spec> BstNodeRef<Mut<'a>, Spec>where
Spec: BstSpec<Data: 'a>,
pub fn dormant(self) -> BstNodeRef<DormantMut, Spec>
Source§impl<Spec> BstNodeRef<DormantMut, Spec>where
Spec: BstSpec,
impl<Spec> BstNodeRef<DormantMut, Spec>where
Spec: BstSpec,
pub unsafe fn awaken<'a>(self) -> BstNodeRef<Mut<'a>, Spec>
Source§impl<Spec> BstNodeRef<Dying, Spec>where
Spec: BstSpec,
impl<Spec> BstNodeRef<Dying, Spec>where
Spec: BstSpec,
Sourcepub unsafe fn into_data<A>(self, allocator: &mut A) -> Spec::Data
pub unsafe fn into_data<A>(self, allocator: &mut A) -> Spec::Data
Examples found in repository?
More examples
crates/competitive/src/data_structure/implicit_splay_tree.rs (line 356)
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/treap.rs (line 394)
380 pub fn remove(&mut self, node_id: BstNodeId<TreapSpec<M, L>>) -> Option<(M::Key, L::Key)> {
381 if !self.node_id_manager.contains(&node_id) {
382 return None;
383 }
384 unsafe {
385 WithParent::resolve_top_down::<TreapSpec<M, L>>(
386 node_id.reborrow_datamut(&mut self.root),
387 );
388 let node = if WithParent::is_root(node_id.reborrow(&self.root)) {
389 WithParent::remove_root(&mut self.root).unwrap_unchecked()
390 } else {
391 WithParent::remove_not_root(node_id.reborrow_mut(&mut self.root))
392 };
393 self.node_id_manager.unregister(node_id);
394 let data = node.into_dying().into_data(self.allocator.deref_mut());
395 Some((data.key.key, data.value.key))
396 }
397 }crates/competitive/src/data_structure/implicit_treap.rs (line 460)
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 }Sourcepub unsafe fn drop_all<A>(self, allocator: &mut A)
pub unsafe fn drop_all<A>(self, allocator: &mut A)
Examples found in repository?
More examples
crates/competitive/src/data_structure/treap.rs (line 268)
265 fn drop(&mut self) {
266 unsafe {
267 if let Some(root) = self.root.take() {
268 root.into_dying().drop_all(self.allocator.deref_mut());
269 }
270 ManuallyDrop::drop(&mut self.allocator);
271 }
272 }
273}
274
275impl<M, L> Treap<M, L>
276where
277 M: MonoidAct<Key: Ord>,
278 L: LazyMapMonoid,
279{
280 pub fn new() -> Self {
281 Self::default()
282 }
283}
284
285impl<M, L, A> Treap<M, L, A>
286where
287 M: MonoidAct<Key: Ord>,
288 L: LazyMapMonoid,
289 A: Allocator<TreapNode<M, L>>,
290{
291 pub fn len(&self) -> usize {
292 self.node_id_manager.len()
293 }
294
295 pub fn is_empty(&self) -> bool {
296 self.node_id_manager.is_empty()
297 }
298
299 pub fn clear(&mut self) {
300 unsafe {
301 if let Some(root) = self.root.take() {
302 root.into_dying().drop_all(self.allocator.deref_mut());
303 }
304 self.node_id_manager.clear();
305 }
306 }Trait Implementations§
impl<'a, Spec> Copy for BstNodeRef<Immut<'a>, Spec>where
Spec: BstSpec<Data: 'a>,
Auto Trait Implementations§
impl<BorrowType, Spec> !Send for BstNodeRef<BorrowType, Spec>
impl<BorrowType, Spec> !Sync for BstNodeRef<BorrowType, Spec>
impl<BorrowType, Spec> Freeze for BstNodeRef<BorrowType, Spec>
impl<BorrowType, Spec> RefUnwindSafe for BstNodeRef<BorrowType, Spec>where
NonNull<BstNode<<Spec as BstSpec>::Data, <Spec as BstSpec>::Parent>>: RefUnwindSafe,
PhantomData<BorrowType>: RefUnwindSafe,
impl<BorrowType, Spec> Unpin for BstNodeRef<BorrowType, Spec>
impl<BorrowType, Spec> UnsafeUnpin for BstNodeRef<BorrowType, Spec>where
NonNull<BstNode<<Spec as BstSpec>::Data, <Spec as BstSpec>::Parent>>: UnsafeUnpin,
PhantomData<BorrowType>: UnsafeUnpin,
impl<BorrowType, Spec> UnwindSafe for BstNodeRef<BorrowType, Spec>where
NonNull<BstNode<<Spec as BstSpec>::Data, <Spec as BstSpec>::Parent>>: UnwindSafe,
PhantomData<BorrowType>: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more