// codesnip-guard: ImplicitSplayTree #[cfg_attr(any(),rustfmt::skip)]pub use self::implicit_splay_tree::ImplicitSplayTree;#[cfg_attr(any(),rustfmt::skip)]mod implicit_splay_tree{use super::{Allocator,LazyMapAct,LazyMapAgg,LazyMapMonoid,LazyMapMonoidWithKeyAct,MemoryPool,binary_search_tree::{BstDataAccess,BstDataMutRef,BstNode,BstRoot,BstSeeker,BstSpec,EqualSide,data::{self,LazyMapElement},node::WithNoParent,seeker::{SeekByAccCond,SeekByRaccCond,SeekBySize},split::Split3},splay_operations};use std::{cmp::Ordering,fmt::{self,Debug},marker::PhantomData,mem::{ManuallyDrop,replace},ops::{DerefMut,RangeBounds}};type ImplicitSplayTreeRoot=BstRoot>;type ImplicitSplayTreeNode=BstNode>;pub struct ImplicitSplayTreeSpec{_marker:PhantomDataT>}pub struct ImplicitSplayTreeDatawhere T:LazyMapMonoid{value:LazyMapElement,size:usize,rev:bool}implDebug for ImplicitSplayTreeDatawhere T:LazyMapMonoid,LazyMapAgg:Debug,LazyMapAct:Debug{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{f.debug_struct("ImplicitSplayTreeData").field("value",&self.value).field("size",&self.size).field("rev",&self.rev).finish()}}implBstDataAccessfor ImplicitSplayTreeDatawhere T:LazyMapMonoid{type Value=usize;fn bst_data(&self)->&Self::Value{&self.size}fn bst_data_mut(&mut self)->&mut Self::Value{&mut self.size}}implBstDataAccessfor ImplicitSplayTreeDatawhere T:LazyMapMonoid{type Value=LazyMapElement;fn bst_data(&self)->&Self::Value{&self.value}fn bst_data_mut(&mut self)->&mut Self::Value{&mut self.value}}implImplicitSplayTreeSpecwhere T:LazyMapMonoidWithKeyAct{fn update_act(mut node:BstDataMutRef<'_,Self>,act:&LazyMapAct){if T::is_act_unit(act){return;}T::act_operate_assign(&mut node.data_mut().value.act,act);node.data_mut().value.key=T::act_key(&node.reborrow().into_data().value.key,act);if let Some(agg)=T::act_agg(&node.reborrow().into_data().value.agg,act){node.data_mut().value.agg=agg;}else{Self::top_down(node.reborrow_datamut());Self::bottom_up(node);}}fn reverse(mut node:BstDataMutRef<'_,Self>){node.swap_children();let data=node.data_mut();T::toggle(&mut data.value.agg);data.rev^=true;}}implBstSpec for ImplicitSplayTreeSpecwhere T:LazyMapMonoidWithKeyAct{type Parent=WithNoParent;type Data=ImplicitSplayTreeData;fn top_down(mut node:BstDataMutRef<'_,Self>){if!T::is_act_unit(&node.reborrow().into_data().value.act){let act=replace(&mut node.data_mut().value.act,T::act_unit());if let Ok(left)=node.reborrow_datamut().left().descend(){Self::update_act(left,&act);}if let Ok(right)=node.reborrow_datamut().right().descend(){Self::update_act(right,&act);}}if node.reborrow().into_data().rev{node.data_mut().rev=false;if let Ok(left)=node.reborrow_datamut().left().descend(){Self::reverse(left);}if let Ok(right)=node.reborrow_datamut().right().descend(){Self::reverse(right);}}}fn bottom_up(mut node:BstDataMutRef<'_,Self>){let mut agg=T::single_agg(&node.reborrow().into_data().value.key);let mut size=1;if let Ok(left)=node.reborrow().left().descend(){let data=left.into_data();agg=T::agg_operate(&data.value.agg,&agg);size+=data.size;}if let Ok(right)=node.reborrow().right().descend(){let data=right.into_data();agg=T::agg_operate(&agg,&data.value.agg);size+=data.size;}let data=node.data_mut();data.value.agg=agg;data.size=size;}fn merge(left:Option>,right:Option>)->Option>{splay_operations::merge(left,right)}fn split(node:Option>,seeker:Seeker,equal_side:EqualSide)->(Option>,Option>)where Seeker:BstSeeker{splay_operations::split(node,seeker,equal_side)}}pub struct ImplicitSplayTree>>where T:LazyMapMonoidWithKeyAct,A:Allocator>{root:Option>,length:usize,allocator:ManuallyDrop,_marker:PhantomDataT>}implDefault for ImplicitSplayTreewhere T:LazyMapMonoidWithKeyAct,A:Allocator>+Default{fn default()->Self{Self{root:None,length:0,allocator:ManuallyDrop::new(A::default()),_marker:PhantomData}}}implDrop for ImplicitSplayTreewhere T:LazyMapMonoidWithKeyAct,A:Allocator>{fn drop(&mut self){unsafe{if let Some(root)=self.root.take(){root.into_dying().drop_all(self.allocator.deref_mut());}ManuallyDrop::drop(&mut self.allocator);}}}implImplicitSplayTreewhere T:LazyMapMonoidWithKeyAct{pub fn new()->Self{Self::default()}pub fn with_capacity(capacity:usize)->Self{Self{root:None,length:0,allocator:ManuallyDrop::new(MemoryPool::with_capacity(capacity)),_marker:PhantomData}}}implImplicitSplayTreewhere T:LazyMapMonoidWithKeyAct,A:Allocator>{fn node(&mut self,key:T::Key)->ImplicitSplayTreeRoot{unsafe{BstRoot::from_data(ImplicitSplayTreeData{value:LazyMapElement::from_key(key),size:1,rev:false},self.allocator.deref_mut())}}#[inline]fn splay(&mut self,seeker:Seeker)->Optionwhere Seeker:BstSeeker>{let(ordering,root)=splay_operations::splay(self.root.take()?,seeker);self.root=Some(root);Some(ordering)}pub fn len(&self)->usize{self.length}pub fn is_empty(&self)->bool{self.length==0}pub fn update(&mut self,range:R,act:LazyMapAct)where R:RangeBounds{let mut split=Split3::seek_by_size(&mut self.root,range);if let Some(root)=split.mid_datamut(){ImplicitSplayTreeSpec::update_act(root,&act);}}pub fn fold(&mut self,range:R)->LazyMapAggwhere R:RangeBounds{let split=Split3::seek_by_size(&mut self.root,range);split.mid().map(|node|node.into_data().value.agg.clone()).unwrap_or_else(T::agg_unit)}pub fn reverse(&mut self,range:R)where R:RangeBounds{let mut split=Split3::seek_by_size(&mut self.root,range);if let Some(root)=split.mid_datamut(){ImplicitSplayTreeSpec::reverse(root);}}pub fn get(&mut self,index:usize)->Option<&T::Key>{if index>=self.length{return None;}self.splay(SeekBySize::new(index));Some(&self.root.as_ref()?.reborrow().into_data().value.key)}pub fn modify(&mut self,index:usize,f:F)where F:FnOnce(&T::Key)->T::Key{assert!(indexOption{if index>=self.length{return None;}self.splay(SeekBySize::new(index));let mut node=self.root.take().unwrap();ImplicitSplayTreeSpec::top_down(node.borrow_datamut());let left=unsafe{node.borrow_mut().left_mut().take()};let right=unsafe{node.borrow_mut().right_mut().take()};self.root=ImplicitSplayTreeSpec::merge(left,right);self.length-=1;let data=unsafe{node.into_dying().into_data(self.allocator.deref_mut())};Some(data.value.key)}pub fn partition_point_acc(&mut self,left:usize,mut pred:F)->usize where F:FnMut(&LazyMapAgg)->bool{let mut split3=Split3::seek_by_size(&mut self.root,left..);let front_size=split3.left().map(|node|node.into_data().size).unwrap_or_default();let split=split3.split_mid(SeekByAccCond::new(|acc|!pred(acc)),EqualSide::Right);let index=split.left().map(|node|node.into_data().size).unwrap_or_default();front_size+index}pub fn rpartition_point_acc(&mut self,right:usize,mut pred:F)->usize where F:FnMut(&LazyMapAgg)->bool{let mut split3=Split3::seek_by_size(&mut self.root,..right);let split=split3.split_mid(SeekByRaccCond::new(|acc|!pred(acc)),EqualSide::Left);split.left().map(|node|node.into_data().size).unwrap_or_default()}pub fn rotate_left(&mut self,mid:usize){assert!(mid<=self.length);if mid==0||mid==self.length{return;}let(left,right)=ImplicitSplayTreeSpec::split(self.root.take(),SeekBySize::new(mid),EqualSide::Right);self.root=ImplicitSplayTreeSpec::merge(right,left);}pub fn rotate_right(&mut self,k:usize){assert!(k<=self.length);self.rotate_left(self.length-k);}}implExtendfor ImplicitSplayTreewhere T:LazyMapMonoidWithKeyAct,A:Allocator>{fn extend(&mut self,iter:I)where I:IntoIterator{let nodes=iter.into_iter().map(|key|self.node(key)).collect::>();let len=nodes.len();let root=if len==0{None}else{let mut stack=Vec::with_capacity(64);stack.push((0,len,None::<(usize,usize)>,false));while let Some((start,end,parent,visited))=stack.pop(){if start==end{continue;}let mid=start+(end-start)/2;if visited{ImplicitSplayTreeSpec::bottom_up(unsafe{BstRoot::new_unchecked(nodes[mid].node)}.borrow_datamut());continue;}if let Some((parent,direction))=parent{let mut parent=nodes[parent].node;unsafe{parent.as_mut().child[direction]=Some(nodes[mid].node)};}stack.push((start,end,parent,true));stack.push((mid+1,end,Some((mid,1)),false));stack.push((start,mid,Some((mid,0)),false));}Some(unsafe{BstRoot::new_unchecked(nodes[len/2].node)})};self.root=ImplicitSplayTreeSpec::merge(self.root.take(),root);self.length+=len;}}} // codesnip-guard: AdditiveOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::additive_operation_impl::AdditiveOperation;#[cfg_attr(any(),rustfmt::skip)]mod additive_operation_impl{use super::*;use std::{marker::PhantomData,ops::{Add,Neg,Sub}};#[doc=" $+$"]pub struct AdditiveOperationwhere T:Clone+Zero+Add{_marker:PhantomDataT>}implMagma for AdditiveOperationwhere T:Clone+Zero+Add{type T=T;#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{x.clone()+y.clone()}}implUnital for AdditiveOperationwhere T:Clone+Zero+Add{#[inline]fn unit()->Self::T{Zero::zero()}}implAssociative for AdditiveOperationwhere T:Clone+Zero+Add{}implCommutative for AdditiveOperationwhere T:Clone+Zero+Add{}implInvertible for AdditiveOperationwhere T:Clone+Zero+Add+Sub+Neg{#[inline]fn inverse(x:&Self::T)->Self::T{-x.clone()}#[inline]fn rinv_operate(x:&Self::T,y:&Self::T)->Self::T{x.clone()-y.clone()}}} // codesnip-guard: Allocator #[cfg_attr(any(),rustfmt::skip)]pub use self::allocator::{Allocator,BoxAllocator,MemoryPool};#[cfg_attr(any(),rustfmt::skip)]mod allocator{use std::{fmt::{self,Debug},marker::PhantomData,mem::{replace,size_of,take},ptr::{self,NonNull,read,write}};#[doc=" # Safety"]#[doc=" Allocations must contain the supplied value and remain valid until deallocation"]#[doc=" or allocator destruction. Live nonzero-sized allocations must not overlap."]pub unsafe trait Allocator{fn allocate(&mut self,value:T)->NonNull;#[doc=" # Safety"]#[doc=" `ptr` must hold a live value allocated by this allocator, with no remaining"]#[doc=" references. The allocation must not be accessed after this call."]unsafe fn deallocate(&mut self,ptr:NonNull)->T;}pub struct MemoryPool{pool:Vec,chunks:Vec>,unused:Vec>}implDebug for MemoryPool{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{f.debug_struct("MemoryPool").field("pool_len",&self.pool.len()).field("chunks",&self.chunks.len()).field("unused",&self.unused.len()).finish()}}implDefault for MemoryPool{fn default()->Self{Self::with_capacity(CAP/1usize.max(size_of::()))}}const CAP:usize=1024;implMemoryPool{pub fn new()->Self{Default::default()}pub fn with_capacity(capacity:usize)->Self{let pool=Vec::with_capacity(capacity.max(1));Self{pool,chunks:Vec::new(),unused:Vec::new()}}}implDrop for MemoryPool{fn drop(&mut self){if size_of::()==0{let mut unused=self.unused.len();for chunk in std::iter::once(&mut self.pool).chain(&mut self.chunks){let removed=unused.min(chunk.len());unsafe{chunk.set_len(chunk.len()-removed)};unused-=removed;}return;}self.chunks.push(take(&mut self.pool));let mut removed=vec![vec![];self.chunks.len()];for p in self.unused.iter(){let p=p.as_ptr();for(chunk,removed)in self.chunks.iter().zip(&mut removed).rev(){let ptr=chunk.as_ptr()as*mut _;let len=chunk.len();if ptr<=p&&pAllocatorfor MemoryPool{fn allocate(&mut self,value:T)->NonNull{if let Some(ptr)=self.unused.pop(){unsafe{write(ptr.as_ptr(),value)};ptr}else{let len=self.pool.len();if len>=self.pool.capacity(){let new_capacity=self.pool.capacity()*2;let new_pool=Vec::with_capacity(new_capacity);self.chunks.push(replace(&mut self.pool,new_pool));}let len=self.pool.len();debug_assert!(len)->T{self.unused.push(ptr);unsafe{read(ptr.as_ptr())}}}#[derive(Debug)]pub struct BoxAllocator(PhantomDataT>);implDefault for BoxAllocator{fn default()->Self{Self(PhantomData)}}unsafe implAllocatorfor BoxAllocator{fn allocate(&mut self,value:T)->NonNull{unsafe{NonNull::new_unchecked(Box::leak(Box::new(value)))}}unsafe fn deallocate(&mut self,ptr:NonNull)->T{unsafe{*Box::from_raw(ptr.as_ptr())}}}} // codesnip-guard: ArrayOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::array_operation_impl::ArrayOperation;#[cfg_attr(any(),rustfmt::skip)]mod array_operation_impl{use super::*;use crate::array;use std::marker::PhantomData;pub struct ArrayOperation{_marker:PhantomDataM>}implMagma for ArrayOperationwhere M:Magma{type T=[M::T;N];#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{array!(|i|M::operate(&x[i],&y[i]);N)}}implUnital for ArrayOperationwhere M:Unital{#[inline]fn unit()->Self::T{array!(||M::unit();N)}}implAssociative for ArrayOperationwhere M:Associative{}implCommutative for ArrayOperationwhere M:Commutative{}implIdempotent for ArrayOperationwhere M:Idempotent{}implInvertible for ArrayOperationwhere M:Invertible{#[inline]fn inverse(x:&Self::T)->Self::T{array!(|i|M::inverse(&x[i]);N)}}} // codesnip-guard: CountingOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::counting_operation_impl::CountingOperation;#[cfg_attr(any(),rustfmt::skip)]mod counting_operation_impl{use super::*;use std::marker::PhantomData;pub struct CountingOperation{_marker:PhantomDataM>}implMagma for CountingOperationwhere M:Magma+Idempotent{type T=(M::T,usize);#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{let z=M::operate(&x.0,&y.0);match(z==x.0,z==y.0){(true,true)=>(z,x.1+y.1),(true,false)=>(z,x.1),(false,true)=>(z,y.1),(false,false)=>(z,1),}}}implUnital for CountingOperationwhere M:Unital+Idempotent{#[inline]fn unit()->Self::T{(M::unit(),0)}}implAssociative for CountingOperationwhere M:Associative+Idempotent{}implCommutative for CountingOperationwhere M:Commutative+Idempotent{}} // codesnip-guard: LastOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::last_operation_impl::LastOperation;#[cfg_attr(any(),rustfmt::skip)]mod last_operation_impl{use super::*;use std::marker::PhantomData;#[doc=" retain the last element"]pub struct LastOperationwhere T:Clone{_marker:PhantomDataT>}implMagma for LastOperationwhere T:Clone{type T=Option;#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{y.as_ref().or(x.as_ref()).cloned()}}implUnital for LastOperationwhere T:Clone{#[inline]fn unit()->Self::T{None}}implAssociative for LastOperationwhere T:Clone{}implIdempotent for LastOperationwhere T:Clone{}} // codesnip-guard: LazyMapMonoid #[cfg_attr(any(),rustfmt::skip)]pub use self::lazy_map::*;#[cfg_attr(any(),rustfmt::skip)]mod lazy_map{use super::*;use std::{cmp::Ordering,marker::PhantomData,ops::{Add,Mul,Sub}};pub type LazyMapAgg=<::AggMonoid as Magma>::T;pub type LazyMapAct=<::ActMonoid as Magma>::T;pub trait LazyMapMonoid{type Key;type AggMonoid:Monoid;type ActMonoid:Monoid;fn single_agg(key:&Self::Key)->LazyMapAgg;fn toggle(_x:&mut LazyMapAgg){}#[inline]fn is_act_unit(act:&LazyMapAct)->bool{::is_unit(act)}#[doc=" Returns `None` when descent is needed; must succeed on single-key aggregates."]fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>;#[inline]fn agg_unit()->LazyMapAgg{::unit()}#[inline]fn act_unit()->LazyMapAct{::unit()}#[inline]fn agg_operate(x:&LazyMapAgg,y:&LazyMapAgg)->LazyMapAgg{::operate(x,y)}#[inline]fn act_operate(x:&LazyMapAct,y:&LazyMapAct)->LazyMapAct{::operate(x,y)}#[inline]fn agg_operate_assign(x:&mut LazyMapAgg,y:&LazyMapAgg){*x=::operate(x,y);}#[inline]fn act_operate_assign(x:&mut LazyMapAct,y:&LazyMapAct){*x=::operate(x,y);}}pub trait LazyMapMonoidWithKeyAct:LazyMapMonoid{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key;}pub struct EmptyActLazy{_marker:PhantomDataM>}implLazyMapMonoid for EmptyActLazywhere M:Monoid{type Key=M::T;type AggMonoid=M;type ActMonoid=();fn single_agg(key:&Self::Key)->LazyMapAgg{key.clone()}fn act_agg(x:&LazyMapAgg,_a:&LazyMapAct)->Option>{Some(x.clone())}}implLazyMapMonoidWithKeyAct for EmptyActLazywhere M:Monoid{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{EmptyAct::act(key,act)}}pub struct EmptyAggActLazy{_marker:PhantomDataT>}implLazyMapMonoid for EmptyAggActLazy{type Key=T;type AggMonoid=();type ActMonoid=();fn single_agg(_key:&Self::Key)->LazyMapAgg{}fn act_agg(_x:&LazyMapAgg,_a:&LazyMapAct)->Option>{Some(())}}implLazyMapMonoidWithKeyAct for EmptyAggActLazywhere T:Clone{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{EmptyAct::act(key,act)}}pub struct FlattenLazy{_marker:PhantomDataM>}implLazyMapMonoid for FlattenLazywhere M:Monoid,M::T:PartialEq{type Key=M::T;type AggMonoid=M;type ActMonoid=M;fn single_agg(key:&Self::Key)->LazyMapAgg{key.clone()}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{Some(M::operate(x,a))}}implLazyMapMonoidWithKeyAct for FlattenLazywhere M:Monoid,M::T:PartialEq{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{FlattenAct::::act(key,act)}}pub struct RangeSumRangeAdd{_marker:PhantomDataT>}implLazyMapMonoid for RangeSumRangeAddwhere T:Copy+Zero+One+Add+Mul+PartialEq{type Key=T;type AggMonoid=(AdditiveOperation,AdditiveOperation);type ActMonoid=AdditiveOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{(*key,T::one())}fn act_agg(&(x,y):&LazyMapAgg,a:&LazyMapAct)->Option>{Some(if Self::is_act_unit(a){(x,y)}else{let a=*a;(x+a*y,y)})}}implLazyMapMonoidWithKeyAct for RangeSumRangeAddwhere T:Copy+Zero+One+Add+Mul+PartialEq{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{FlattenAct::::act(key,act)}}pub struct RangeSumRangeLinear{_marker:PhantomDataT>}implLazyMapMonoid for RangeSumRangeLinearwhere T:Copy+Zero+One+Add+Mul+PartialEq{type Key=T;type AggMonoid=(AdditiveOperation,AdditiveOperation);type ActMonoid=LinearOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{(*key,T::one())}fn act_agg(&(x,y):&LazyMapAgg,&(a,b):&LazyMapAct)->Option>{Some((a*x+b*y,y))}}implLazyMapMonoidWithKeyAct for RangeSumRangeLinearwhere T:Copy+Zero+One+Add+Mul+PartialEq{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{LinearAct::act(key,act)}}pub struct RangePowerSumRangeLinear{_marker:PhantomDataT>}implLazyMapMonoid for RangePowerSumRangeLinearwhere T:Copy+Zero+One+Add+Mul+PartialEq{type Key=T;type AggMonoid=ArrayOperation,K>;type ActMonoid=LinearOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{let mut power=T::one();std::array::from_fn(|k|{if k!=0{power=power**key;}power})}fn act_agg(x:&LazyMapAgg,&(a,b):&LazyMapAct)->Option>{let mut coefficients=[T::one();K];let mut result=*x;for k in 1..K{coefficients[k]=a*coefficients[k-1];for j in(1..k).rev(){coefficients[j]=b*coefficients[j]+a*coefficients[j-1];}coefficients[0]=b*coefficients[0];result[k]=coefficients[..=k].iter().zip(x).fold(T::zero(),|sum,(&c,&p)|sum+c*p);}Some(result)}}implLazyMapMonoidWithKeyAct for RangePowerSumRangeLinearwhere T:Copy+Zero+One+Add+Mul+PartialEq{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{LinearAct::act(key,act)}}pub struct RangeSumRangeUpdate{_marker:PhantomDataT>}implLazyMapMonoid for RangeSumRangeUpdatewhere T:Copy+Zero+One+Add+Mul+PartialEq{type Key=T;type AggMonoid=(AdditiveOperation,AdditiveOperation);type ActMonoid=LastOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{(*key,T::one())}fn act_agg(&(x,y):&LazyMapAgg,a:&LazyMapAct)->Option>{Some((a.map(|a|a*y).unwrap_or(x),y))}}implLazyMapMonoidWithKeyAct for RangeSumRangeUpdatewhere T:Copy+Zero+One+Add+Mul+PartialEq{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{UpdateAct::act(key,act)}}pub struct RangeMaxRangeUpdate{_marker:PhantomDataT>}implLazyMapMonoid for RangeMaxRangeUpdatewhere T:Clone+PartialEq+Ord+Bounded{type Key=T;type AggMonoid=MaxOperation;type ActMonoid=LastOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{key.clone()}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{Some(a.as_ref().unwrap_or(x).clone())}}implLazyMapMonoidWithKeyAct for RangeMaxRangeUpdatewhere T:Clone+PartialEq+Ord+Bounded{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{UpdateAct::act(key,act)}}pub struct RangeMinRangeUpdate{_marker:PhantomDataT>}implLazyMapMonoid for RangeMinRangeUpdatewhere T:Clone+PartialEq+Ord+Bounded{type Key=T;type AggMonoid=MinOperation;type ActMonoid=LastOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{key.clone()}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{Some(a.as_ref().unwrap_or(x).clone())}}implLazyMapMonoidWithKeyAct for RangeMinRangeUpdatewhere T:Clone+PartialEq+Ord+Bounded{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{UpdateAct::act(key,act)}}pub struct RangeMaxRangeAdd{_marker:PhantomDataT>}implLazyMapMonoid for RangeMaxRangeAddwhere T:Clone+Ord+Bounded+Zero+Add{type Key=T;type AggMonoid=MaxOperation;type ActMonoid=AdditiveOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{key.clone()}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{Some(if Self::is_act_unit(a){x.clone()}else{x.clone()+a.clone()})}}implLazyMapMonoidWithKeyAct for RangeMaxRangeAddwhere T:Clone+Ord+Bounded+Zero+Add{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{FlattenAct::::act(key,act)}}pub struct RangeMinRangeAdd{_marker:PhantomDataT>}implLazyMapMonoid for RangeMinRangeAddwhere T:Clone+Ord+Bounded+Zero+Add{type Key=T;type AggMonoid=MinOperation;type ActMonoid=AdditiveOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{key.clone()}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{Some(if Self::is_act_unit(a){x.clone()}else{x.clone()+a.clone()})}}implLazyMapMonoidWithKeyAct for RangeMinRangeAddwhere T:Clone+Ord+Bounded+Zero+Add{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{FlattenAct::::act(key,act)}}pub struct RangeMinCountRangeAdd{_marker:PhantomDataT>}implLazyMapMonoid for RangeMinCountRangeAddwhere T:Clone+Ord+Bounded+Zero+Add{type Key=T;type AggMonoid=CountingOperation>;type ActMonoid=AdditiveOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{(key.clone(),1)}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{Some(if x.1==0{x.clone()}else{(x.0 .clone()+a.clone(),x.1)})}}implLazyMapMonoidWithKeyAct for RangeMinCountRangeAddwhere T:Clone+Ord+Bounded+Zero+Add{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{FlattenAct::::act(key,act)}}#[derive(Debug,Clone,Copy,PartialEq,Eq)]pub struct RangeChminChmaxAdd{lb:T,ub:T,bias:T}implRangeChminChmaxAddwhere T:Zero+Bounded{pub fn chmin(x:T)->Self{Self{lb:T::minimum(),ub:x,bias:T::zero()}}pub fn chmax(x:T)->Self{Self{lb:x,ub:T::maximum(),bias:T::zero()}}pub fn add(x:T)->Self where T:Copy+Ord+Add{Self{lb:T::minimum()+x.max(T::zero()),ub:T::maximum()+x.min(T::zero()),bias:x}}}implMagma for RangeChminChmaxAddwhere T:Copy+Zero+Ord+Bounded+Add{type T=Self;fn operate(x:&Self::T,y:&Self::T)->Self::T{Self{lb:(x.lb+y.bias).max(y.lb).min(y.ub),ub:(x.ub+y.bias).max(y.lb).min(y.ub),bias:x.bias+y.bias}}}implAssociative for RangeChminChmaxAddwhere T:Copy+Zero+Ord+Bounded+Add{}implUnital for RangeChminChmaxAddwhere T:Copy+Zero+Ord+Bounded+Add{fn unit()->Self::T{Self{lb:T::minimum(),ub:T::maximum(),bias:T::zero()}}}#[derive(Debug,Clone,PartialEq,Eq)]pub struct RangeSumRangeChminChmaxAdd{min:T,max:T,min2:T,max2:T,pub sum:T,size:T,n_min:T,n_max:T}implRangeSumRangeChminChmaxAddwhere T:Copy+Zero+One+Ord+Bounded+Add+Sub+Mul+PartialEq{pub fn single(key:T,size:T)->Self{Self{min:key,max:key,min2:T::maximum(),max2:T::minimum(),sum:key*size,size,n_min:size,n_max:size}}}implMagma for RangeSumRangeChminChmaxAddwhere T:Copy+Zero+One+Ord+Bounded+Add+Sub+Mul+PartialEq{type T=Self;fn operate(x:&Self::T,y:&Self::T)->Self::T{Self{min:x.min.min(y.min),max:x.max.max(y.max),min2:if x.min==y.min{x.min2.min(y.min2)}else if x.min2<=y.min{x.min2}else if y.min2<=x.min{y.min2}else{x.min.max(y.min)},max2:if x.max==y.max{x.max2.max(y.max2)}else if x.max2>=y.max{x.max2}else if y.max2>=x.max{y.max2}else{x.max.min(y.max)},sum:x.sum+y.sum,size:x.size+y.size,n_min:match x.min.cmp(&y.min){Ordering::Less=>x.n_min,Ordering::Equal=>x.n_min+y.n_min,Ordering::Greater=>y.n_min,},n_max:match x.max.cmp(&y.max){Ordering::Less=>y.n_max,Ordering::Equal=>x.n_max+y.n_max,Ordering::Greater=>x.n_max,}}}}implAssociative for RangeSumRangeChminChmaxAddwhere T:Copy+Zero+One+Ord+Bounded+Add+Sub+Mul+PartialEq{}implUnital for RangeSumRangeChminChmaxAddwhere T:Copy+Zero+One+Ord+Bounded+Add+Sub+Mul+PartialEq{fn unit()->Self::T{Self{min:T::maximum(),max:T::minimum(),min2:T::maximum(),max2:T::minimum(),sum:T::zero(),size:T::zero(),n_min:T::zero(),n_max:T::zero()}}}implMonoidAct for RangeChminChmaxAddwhere T:Copy+Zero+Ord+Bounded+Add{type Key=T;type Act=RangeChminChmaxAdd;type ActMonoid=RangeChminChmaxAdd;fn act(x:&Self::Key,a:&Self::Act)->Self::Key{(*x+a.bias).max(a.lb).min(a.ub)}}implLazyMapMonoid for RangeSumRangeChminChmaxAddwhere T:Copy+Zero+One+Ord+Bounded+Add+Sub+Mul+PartialEq{type Key=T;type AggMonoid=Self;type ActMonoid=RangeChminChmaxAdd;fn single_agg(&key:&Self::Key)->LazyMapAgg{Self::single(key,T::one())}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{if Self::is_act_unit(a){return Some(x.clone());}if x.size.is_zero(){return Some(Self::unit());}let lb=a.lb-a.bias;let ub=a.ub-a.bias;let min=x.min.max(lb);let max=x.max.min(ub);Some(if min>=max{Self::single(RangeChminChmaxAdd::act(&x.min,a),x.size)}else if x.min2==x.max{let mut x=x.clone();let min=min+a.bias;let max=max+a.bias;x.min=min;x.max2=min;x.max=max;x.min2=max;x.sum=min*x.n_min+max*x.n_max;x}else if lbLazyMapMonoidWithKeyAct for RangeSumRangeChminChmaxAddwhere T:Copy+Zero+One+Ord+Bounded+Add+Sub+Mul+PartialEq{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{RangeChminChmaxAdd::act(key,act)}}} // codesnip-guard: LinearOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::linear_operation_impl::LinearOperation;#[cfg_attr(any(),rustfmt::skip)]mod linear_operation_impl{use super::*;use std::{marker::PhantomData,ops::{Add,Div,Mul,Neg,Sub}};#[doc=" $(a, b) \\circ (c, d) = \\lambda x. c \\times (a \\times x + b) + d$"]pub struct LinearOperationwhere T:Clone+Zero+Add+One+Mul{_marker:PhantomDataT>}implLinearOperationwhere T:Clone+Zero+Add+One+Mul{pub fn apply(f:&(T,T),x:&T)->T{f.0 .clone()*x.clone()+f.1 .clone()}}implMagma for LinearOperationwhere T:Clone+Zero+One+Add+Mul{type T=(T,T);#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{(y.0 .clone()*x.0 .clone(),y.0 .clone()*x.1 .clone()+y.1 .clone())}}implUnital for LinearOperationwhere T:Clone+Zero+One+Add+Mul{#[inline]fn unit()->Self::T{(One::one(),Zero::zero())}}implAssociative for LinearOperationwhere T:Clone+Zero+One+Add+Mul{}implInvertible for LinearOperationwhere T:Clone+Zero+One+Add+Sub+Neg+Mul+Div{fn inverse(x:&Self::T)->Self::T{let y=::one().div(x.0 .clone());(y.clone(),-y.mul(x.1 .clone()))}}} // codesnip-guard: MaxOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::max_operation_impl::MaxOperation;#[cfg_attr(any(),rustfmt::skip)]mod max_operation_impl{use super::*;use std::marker::PhantomData;#[doc=" binary operation to select larger element"]pub struct MaxOperationwhere T:Clone+Ord+Bounded{_marker:PhantomDataT>}implMagma for MaxOperationwhere T:Clone+Ord+Bounded{type T=T;#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{x.max(y).clone()}}implUnital for MaxOperationwhere T:Clone+Ord+Bounded{#[inline]fn unit()->Self::T{::minimum()}}implAssociative for MaxOperationwhere T:Clone+Ord+Bounded{}implCommutative for MaxOperationwhere T:Clone+Ord+Bounded{}implIdempotent for MaxOperationwhere T:Clone+Ord+Bounded{}} // codesnip-guard: MinOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::min_operation_impl::MinOperation;#[cfg_attr(any(),rustfmt::skip)]mod min_operation_impl{use super::*;use std::marker::PhantomData;#[doc=" binary operation to select smaller element"]pub struct MinOperationwhere T:Clone+Ord+Bounded{_marker:PhantomDataT>}implMagma for MinOperationwhere T:Clone+Ord+Bounded{type T=T;#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{x.min(y).clone()}}implUnital for MinOperationwhere T:Clone+Ord+Bounded{#[inline]fn unit()->Self::T{::maximum()}}implAssociative for MinOperationwhere T:Clone+Ord+Bounded{}implCommutative for MinOperationwhere T:Clone+Ord+Bounded{}implIdempotent for MinOperationwhere T:Clone+Ord+Bounded{}} // codesnip-guard: MonoidAct #[cfg_attr(any(),rustfmt::skip)]pub use self::action::*;#[cfg_attr(any(),rustfmt::skip)]mod action{use super::*;use std::{marker::PhantomData,ops::{Add,Mul}};pub trait MonoidAct{type Key;type Act:Clone;type ActMonoid:Monoid;fn act(x:&Self::Key,a:&Self::Act)->Self::Key;fn act_assign(x:&mut Self::Key,a:&Self::Act){*x=Self::act(x,a);}fn unit()->Self::Act{::unit()}fn operate(x:&Self::Act,y:&Self::Act)->Self::Act{::operate(x,y)}fn operate_assign(x:&mut Self::Act,y:&Self::Act){*x=::operate(x,y);}}pub struct EmptyAct{_marker:PhantomDataT>}implMonoidAct for EmptyActwhere T:Clone{type Key=T;type Act=();type ActMonoid=();fn act(x:&Self::Key,_a:&Self::Act)->Self::Key{x.clone()}}pub struct FlattenAct{_marker:PhantomDataM>}implMonoidAct for FlattenActwhere M:Monoid{type Key=M::T;type Act=M::T;type ActMonoid=M;fn act(x:&Self::Key,a:&Self::Act)->Self::Key{M::operate(x,a)}}pub struct LinearAct{_marker:PhantomDataT>}implMonoidAct for LinearActwhere T:Clone+Zero+One+Add+Mul{type Key=T;type Act=(T,T);type ActMonoid=LinearOperation;fn act(x:&Self::Key,(a,b):&Self::Act)->Self::Key{a.clone()*x.clone()+b.clone()}}pub struct UpdateAct{_marker:PhantomDataT>}implMonoidAct for UpdateActwhere T:Clone{type Key=T;type Act=Option;type ActMonoid=LastOperation;fn act(x:&Self::Key,a:&Self::Act)->Self::Key{a.as_ref().unwrap_or(x).clone()}}} // codesnip-guard: TupleOperation #[cfg_attr(any(),rustfmt::skip)]mod tuple_operation_impl{use super::*;macro_rules!impl_tuple_operation{(@impl)=>{impl Magma for(){type T=();fn operate(_x:&Self::T,_y:&Self::T)->Self::T{}}impl Unital for(){fn unit()->Self::T{}}impl Associative for(){}impl Commutative for(){}impl Idempotent for(){}impl Invertible for(){fn inverse(_x:&Self::T)->Self::T{}}};(@impl$($T:ident$i:tt)*)=>{impl<$($T:Magma),*>Magma for($($T,)*){type T=($(<$T as Magma>::T,)*);fn operate(x:&Self::T,y:&Self::T)->Self::T{($(<$T as Magma>::operate(&x.$i,&y.$i),)*)}}impl<$($T:Unital),*>Unital for($($T,)*){fn unit()->Self::T{($(<$T as Unital>::unit(),)*)}}impl<$($T:Associative),*>Associative for($($T,)*){}impl<$($T:Commutative),*>Commutative for($($T,)*){}impl<$($T:Idempotent),*>Idempotent for($($T,)*){}impl<$($T:Invertible),*>Invertible for($($T,)*){fn inverse(x:&Self::T)->Self::T{($(<$T as Invertible>::inverse(&x.$i),)*)}}};(@inner$($T:ident$i:tt)*;$U:ident$j:tt$($t:tt)*)=>{impl_tuple_operation!(@impl$($T$i)*);impl_tuple_operation!(@inner$($T$i)*$U$j;$($t)*);};(@inner$($T:ident$i:tt)*;)=>{impl_tuple_operation!(@impl$($T$i)*);};($($t:tt)*)=>{impl_tuple_operation!(@inner;$($t)*);};}impl_tuple_operation!(A 0 B 1 C 2 D 3 E 4 F 5 G 6 H 7 I 8 J 9);} // codesnip-guard: _splay_operations #[cfg_attr(any(),rustfmt::skip)]pub mod splay_operations{use super::binary_search_tree::{BstDataMutRef,BstNodePtr,BstRoot,BstSeeker,BstSpec,EqualSide,node::{WithNoParent,WithParent},seeker::SeekRight};use std::{cmp::Ordering,mem::MaybeUninit};pub mod with_parent{use super::{BstDataMutRef,BstNodePtr,BstSpec,MaybeUninit,WithParent};type NodePtr=BstNodePtr<::Data,::Parent>;#[inline]unsafe fn internal_parent(node:NodePtr)->Result<(NodePtr,usize),Option>>where Spec:BstSpec>{let Some(parent)=(unsafe{node.as_ref().parent.parent})else{return Err(None);};let children=unsafe{parent.as_ref().child};if children[0]==Some(node){Ok((parent,0))}else if children[1]==Some(node){Ok((parent,1))}else{Err(Some(parent))}}#[inline(always)]unsafe fn rotate_at(mut node:NodePtr,mut parent:NodePtr,direction:usize)where Spec:BstSpec>{let middle=unsafe{node.as_ref().child[direction^1]};unsafe{parent.as_mut().child[direction]=middle;if let Some(mut middle)=middle{middle.as_mut().parent.parent=Some(parent);}node.as_mut().child[direction^1]=Some(parent);parent.as_mut().parent.parent=Some(node);}}#[inline(always)]pub unsafe fn rotate(mut node:NodePtr)where Spec:BstSpec>{let(parent,direction)=unsafe{internal_parent::(node)}.expect("an auxiliary root cannot be rotated");unsafe{node.as_mut().parent.parent=parent.as_ref().parent.parent;if let Ok((mut grandparent,direction))=internal_parent::(parent){grandparent.as_mut().child[direction]=Some(node);}rotate_at::(node,parent,direction);Spec::bottom_up(BstDataMutRef::new_unchecked(parent));}}#[doc=" Moves `node` to the root of its auxiliary tree and returns the previous root."]#[doc=""]#[doc=" # Safety"]#[doc=""]#[doc=" `node` and every pointer reachable through its auxiliary-parent chain must"]#[doc=" refer to live nodes of the same tree."]#[inline(always)]pub unsafe fn splay(node:NodePtr)->NodePtrwhere Spec:BstSpec>{let mut inline_stack=[const{MaybeUninit::uninit()};64];let mut inline_len=0;let mut overflow_stack=Vec::new();let mut current=node;loop{if inline_len(current)}{Ok((parent,_))=>current=parent,Err(_)=>break,}}for&node in overflow_stack.iter().rev(){unsafe{Spec::top_down(BstDataMutRef::new_unchecked(node))};}while inline_len>0{inline_len-=1;unsafe{Spec::top_down(BstDataMutRef::new_unchecked(*inline_stack[inline_len].assume_init_ref()));}}while let Ok((parent,node_direction))=unsafe{internal_parent::(node)}{if let Ok((_,parent_direction))=unsafe{internal_parent::(parent)}{if node_direction==parent_direction{unsafe{rotate::(parent)};}else{unsafe{rotate::(node)};}}unsafe{rotate::(node)};}unsafe{Spec::bottom_up(BstDataMutRef::new_unchecked(node))};current}#[doc=" Moves `node` to the root by propagating only the nodes involved in each rotation and"]#[doc=" returns the previous root."]#[doc=""]#[doc=" # Safety"]#[doc=""]#[doc=" `node` and every pointer reachable through its auxiliary-parent chain must refer to live"]#[doc=" nodes of the same tree. Propagating an ancestor after its descendant must be valid for"]#[doc=" `Spec`."]#[inline(always)]pub unsafe fn splay_with_local_top_down(mut node:NodePtr)->NodePtrwhere Spec:BstSpec>{let mut current=node;unsafe{Spec::top_down(BstDataMutRef::new_unchecked(node))};while let Ok((parent,_))=unsafe{internal_parent::(node)}{match unsafe{internal_parent::(parent)}{Ok((grandparent,_))=>{current=grandparent;unsafe{Spec::top_down(BstDataMutRef::new_unchecked(grandparent));Spec::top_down(BstDataMutRef::new_unchecked(parent));Spec::top_down(BstDataMutRef::new_unchecked(node));let node_direction=usize::from(parent.as_ref().child[1]==Some(node));let parent_direction=usize::from(grandparent.as_ref().child[1]==Some(parent));node.as_mut().parent.parent=grandparent.as_ref().parent.parent;if let Ok((mut ancestor,direction))=internal_parent::(grandparent){ancestor.as_mut().child[direction]=Some(node);}if node_direction==parent_direction{rotate_at::(parent,grandparent,parent_direction);rotate_at::(node,parent,node_direction);Spec::bottom_up(BstDataMutRef::new_unchecked(grandparent));Spec::bottom_up(BstDataMutRef::new_unchecked(parent));}else{rotate_at::(node,parent,node_direction);rotate_at::(node,grandparent,parent_direction);Spec::bottom_up(BstDataMutRef::new_unchecked(parent));Spec::bottom_up(BstDataMutRef::new_unchecked(grandparent));}}}Err(ancestor)=>{current=parent;unsafe{Spec::top_down(BstDataMutRef::new_unchecked(parent));Spec::top_down(BstDataMutRef::new_unchecked(node));let direction=usize::from(parent.as_ref().child[1]==Some(node));node.as_mut().parent.parent=ancestor;rotate_at::(node,parent,direction);Spec::bottom_up(BstDataMutRef::new_unchecked(parent));}}}}unsafe{Spec::bottom_up(BstDataMutRef::new_unchecked(node))};current}}pub fn rooted_heavy_order(vertices_size:usize,edges:&[(usize,usize)])->Vec<(usize,usize,bool)>{if vertices_size==0{return Vec::new();}let mut head=vec![usize::MAX;vertices_size];let mut to=Vec::with_capacity(edges.len()*2);let mut next=Vec::with_capacity(edges.len()*2);for&(u,v)in edges{to.push(v);next.push(head[u]);head[u]=to.len()-1;to.push(u);next.push(head[v]);head[v]=to.len()-1;}let mut parent=vec![usize::MAX;vertices_size];let mut stack=vec![0];let mut order=Vec::with_capacity(vertices_size-1);parent[0]=0;while let Some(u)=stack.pop(){let mut edge=head[u];while edge!=usize::MAX{let v=to[edge];if parent[v]==usize::MAX{parent[v]=u;order.push((v,u));stack.push(v);}edge=next[edge];}}let mut size=vec![1usize;vertices_size];let mut heavy=vec![usize::MAX;vertices_size];for&(child,parent)in order.iter().rev(){size[parent]+=size[child];if heavy[parent]==usize::MAX||size[heavy[parent]](root:BstRoot,mut seeker:Seeker)->(Ordering,BstRoot)where Spec:BstSpec>,Seeker:BstSeeker{let mut root=root;let mut left_subtree=None;let mut right_subtree=None;let mut left_entry=&mut left_subtree;let mut right_entry=&mut right_subtree;let mut inline_stack=[None;24];let mut inline_len=0;let mut overflow_stack=vec![];macro_rules!push_node{($node:expr)=>{if inline_len{*left_entry=Some($node.node);push_node!($node.node);left_entry=unsafe{&mut$node.node.as_mut().child[1]};};(@right$node:ident)=>{*right_entry=Some($node.node);push_node!($node.node);right_entry=unsafe{&mut$node.node.as_mut().child[0]};};}let root_ordering=loop{Spec::top_down(root.borrow_datamut());match seeker.bst_seek(root.reborrow()){Ordering::Greater=>{let Some(mut child)=(unsafe{root.borrow_mut().left_mut().take()})else{break Ordering::Greater;};Spec::top_down(child.borrow_datamut());match seeker.bst_seek(child.reborrow()){Ordering::Greater=>{let Some(mut grandchild)=(unsafe{child.borrow_mut().left_mut().take()})else{add!(@right root);root=child;break Ordering::Greater;};Spec::top_down(grandchild.borrow_datamut());let child_right=unsafe{child.borrow_mut().right_mut().take()};if let Some(child_right)=child_right{unsafe{root.borrow_mut().left_mut().set(child_right)};}Spec::bottom_up(root.borrow_datamut());unsafe{child.borrow_mut().right_mut().set(root)};add!(@right child);root=grandchild;}Ordering::Equal=>{add!(@right root);root=child;break Ordering::Equal;}Ordering::Less=>{let Some(mut grandchild)=(unsafe{child.borrow_mut().right_mut().take()})else{add!(@right root);root=child;break Ordering::Less;};Spec::top_down(grandchild.borrow_datamut());add!(@right root);add!(@left child);root=grandchild;}}}Ordering::Equal=>break Ordering::Equal,Ordering::Less=>{let Some(mut child)=(unsafe{root.borrow_mut().right_mut().take()})else{break Ordering::Less;};Spec::top_down(child.borrow_datamut());match seeker.bst_seek(child.reborrow()){Ordering::Greater=>{let Some(mut grandchild)=(unsafe{child.borrow_mut().left_mut().take()})else{add!(@left root);root=child;break Ordering::Greater;};Spec::top_down(grandchild.borrow_datamut());add!(@left root);add!(@right child);root=grandchild;}Ordering::Equal=>{add!(@left root);root=child;break Ordering::Equal;}Ordering::Less=>{let Some(mut grandchild)=(unsafe{child.borrow_mut().right_mut().take()})else{add!(@left root);root=child;break Ordering::Less;};Spec::top_down(grandchild.borrow_datamut());let child_left=unsafe{child.borrow_mut().left_mut().take()};if let Some(child_left)=child_left{unsafe{root.borrow_mut().right_mut().set(child_left)};}Spec::bottom_up(root.borrow_datamut());unsafe{child.borrow_mut().left_mut().set(root)};add!(@left child);root=grandchild;}}}}};*left_entry=unsafe{root.borrow_mut().left_mut().take()}.map(|node|node.node);*right_entry=unsafe{root.borrow_mut().right_mut().take()}.map(|node|node.node);unsafe{root.node.as_mut().child[0]=left_subtree;root.node.as_mut().child[1]=right_subtree;while let Some(node)=overflow_stack.pop(){Spec::bottom_up(BstRoot::new_unchecked(node).borrow_datamut());}while inline_len>0{inline_len-=1;let node=inline_stack[inline_len].unwrap_unchecked();Spec::bottom_up(BstRoot::new_unchecked(node).borrow_datamut());}}Spec::bottom_up(root.borrow_datamut());(root_ordering,root)}#[inline]pub fn merge(left:Option>,right:Option>)->Option>where Spec:BstSpec>{match(left,right){(None,None)=>None,(None,Some(root))|(Some(root),None)=>Some(root),(Some(left),Some(mut right))if right.reborrow().left().descend().is_err()=>{Spec::top_down(right.borrow_datamut());unsafe{right.borrow_mut().left_mut().set(left)};Spec::bottom_up(right.borrow_datamut());Some(right)}(Some(left),Some(right))=>{let(_,mut root)=splay(left,SeekRight::default());unsafe{root.borrow_mut().right_mut().set(right)};Spec::bottom_up(root.borrow_datamut());Some(root)}}}#[inline]pub fn split(root:Option>,seeker:Seeker,equal_side:EqualSide)->(Option>,Option>)where Spec:BstSpec>,Seeker:BstSeeker{let Some(root)=root else{return(None,None);};let(ordering,mut root)=splay(root,seeker);if equal_side.goes_left(ordering){let right=unsafe{root.borrow_mut().right_mut().take()};Spec::bottom_up(root.borrow_datamut());(Some(root),right)}else{let left=unsafe{root.borrow_mut().left_mut().take()};Spec::bottom_up(root.borrow_datamut());(left,Some(root))}}} // codesnip-guard: algebra #[cfg_attr(any(),rustfmt::skip)]pub use self::magma::*;#[cfg_attr(any(),rustfmt::skip)]mod magma{#![doc=" algebraic traits"]#[doc=" binary operaion: $T \\circ T \\to T$"]pub trait Magma{#[doc=" type of operands: $T$"]type T:Clone;#[doc=" binary operaion: $\\circ$"]fn operate(x:&Self::T,y:&Self::T)->Self::T;fn reverse_operate(x:&Self::T,y:&Self::T)->Self::T{Self::operate(y,x)}fn operate_assign(x:&mut Self::T,y:&Self::T){*x=Self::operate(x,y);}}#[doc=" $\\forall a,\\forall b,\\forall c \\in T, (a \\circ b) \\circ c = a \\circ (b \\circ c)$"]pub trait Associative:Magma{}#[doc=" associative binary operation"]pub trait SemiGroup:Magma+Associative{}implSemiGroup for S where S:Magma+Associative{}#[doc=" $\\exists e \\in T, \\forall a \\in T, e \\circ a = a \\circ e = a$"]pub trait Unital:Magma{#[doc=" identity element: $e$"]fn unit()->Self::T;fn is_unit(x:&Self::T)->bool where Self::T:PartialEq{x==&Self::unit()}fn set_unit(x:&mut Self::T){*x=Self::unit();}}pub trait ExpBits{type Iter:Iterator;fn bits(self)->Self::Iter;}pub trait SignedExpBits{type T:ExpBits;fn neg_and_bits(self)->(bool,Self::T);}pub struct Bits{n:T}macro_rules!impl_exp_bits_for_uint{($($t:ty)*)=>{$(impl Iterator for Bits<$t>{type Item=bool;fn next(&mut self)->Option{if self.n==0{None}else{let bit=(self.n&1)==1;self.n>>=1;Some(bit)}}}impl ExpBits for$t{type Iter=Bits<$t>;fn bits(self)->Self::Iter{Bits{n:self}}}impl SignedExpBits for$t{type T=$t;fn neg_and_bits(self)->(bool,Self::T){(false,self)}})*};}impl_exp_bits_for_uint!(u8 u16 u32 u64 u128 usize);macro_rules!impl_signed_exp_bits_for_sint{($($s:ty,$u:ty;)*)=>{$(impl SignedExpBits for$s{type T=$u;fn neg_and_bits(self)->(bool,Self::T){(self<0,self.unsigned_abs())}})*};}impl_signed_exp_bits_for_sint!(i8,u8;i16,u16;i32,u32;i64,u64;i128,u128;isize,usize;);#[doc=" associative binary operation and an identity element"]pub trait Monoid:SemiGroup+Unital{#[doc=" binary exponentiation: $x^n = x\\circ\\ddots\\circ x$"]fn pow(mut x:Self::T,exp:E)->Self::T where E:ExpBits{let mut bits=exp.bits();let Some(first)=bits.next()else{return Self::unit();};let mut res=if first{x.clone()}else{Self::unit()};for bit in bits{x=Self::operate(&x,&x);if bit{res=Self::operate(&res,&x);}}res}fn fold(iter:I)->Self::T where I:IntoIterator{let mut iter=iter.into_iter();if let Some(item)=iter.next(){iter.fold(item,|acc,x|Self::operate(&acc,&x))}else{Self::unit()}}}implMonoid for M where M:SemiGroup+Unital{}#[doc=" $\\exists e \\in T, \\forall a \\in T, \\exists b,c \\in T, b \\circ a = a \\circ c = e$"]pub trait Invertible:Magma+Unital{#[doc=" $a$ where $a \\circ x = e$"]fn inverse(x:&Self::T)->Self::T;fn rinv_operate(x:&Self::T,y:&Self::T)->Self::T{Self::operate(x,&Self::inverse(y))}fn rinv_operate_assign(x:&mut Self::T,y:&Self::T){*x=Self::rinv_operate(x,y);}}#[doc=" associative binary operation and an identity element and inverse elements"]pub trait Group:Monoid+Invertible{fn signed_pow(x:Self::T,exp:E)->Self::T where E:SignedExpBits{let(neg,exp)=E::neg_and_bits(exp);let res=Self::pow(x,exp);if neg{Self::inverse(&res)}else{res}}}implGroup for G where G:Monoid+Invertible{}#[doc=" $\\forall a,\\forall b \\in T, a \\circ b = b \\circ a$"]pub trait Commutative:Magma{}#[doc=" commutative monoid"]pub trait AbelianMonoid:Monoid+Commutative{}implAbelianMonoid for M where M:Monoid+Commutative{}#[doc=" commutative group"]pub trait AbelianGroup:Group+Commutative{}implAbelianGroup for G where G:Group+Commutative{}#[doc=" $\\forall a \\in T, a \\circ a = a$"]pub trait Idempotent:Magma{}#[doc=" idempotent monoid"]pub trait IdempotentMonoid:Monoid+Idempotent{}implIdempotentMonoid for M where M:Monoid+Idempotent{}#[macro_export]macro_rules!monoid_fold{($m:ty)=>{<$m as Unital>::unit()};($m:ty,)=>{<$m as Unital>::unit()};($m:ty,$f:expr)=>{$f};($m:ty,$f:expr,$($ff:expr),*)=>{<$m as Magma>::operate(&($f),&monoid_fold!($m,$($ff),*))};}#[macro_export]macro_rules!define_monoid{($Name:ident,$t:ty,|$x:ident,$y:ident|$op:expr,$unit:expr)=>{struct$Name;impl Magma for$Name{type T=$t;fn operate($x:&Self::T,$y:&Self::T)->Self::T{$op}}impl Unital for$Name{fn unit()->Self::T{$unit}}impl Associative for$Name{}};}} // codesnip-guard: array #[cfg_attr(any(),rustfmt::skip)]mod array{#[macro_export]macro_rules!array{[@inner$data:ident=[$init:expr;$len:expr]]=>{{use::std::mem::{ManuallyDrop,MaybeUninit};let mut$data:[MaybeUninit<_>;$len]=unsafe{MaybeUninit::uninit().assume_init()};$init;#[repr(C)]union __Transmuter{src:ManuallyDrop<[MaybeUninit;N]>,dst:ManuallyDrop<[T;N]>,}ManuallyDrop::into_inner(unsafe{__Transmuter{src:ManuallyDrop::new($data)}.dst})}};[||$e:expr;$len:expr]=>{$crate::array![@inner data=[data.iter_mut().for_each(|item|*item=MaybeUninit::new($e));$len]]};[|$i:pat_param|$e:expr;$len:expr]=>{$crate::array![@inner data=[data.iter_mut().enumerate().for_each(|($i,item)|*item=MaybeUninit::new($e));$len]]};[$e:expr;$len:expr]=>{{let e=$e;$crate::array![||Clone::clone(&e);$len]}};}} // codesnip-guard: binary_search_tree #[cfg_attr(any(),rustfmt::skip)]pub mod binary_search_tree{use super::{Allocator,LazyMapAct,LazyMapAgg,LazyMapMonoid,LazyMapMonoidWithKeyAct,Monoid,MonoidAct};pub use data::BstDataAccess;pub use node::{BstDataMutRef,BstEdgeHandle,BstImmutRef,BstNode,BstNodePtr,BstNodeRef,BstRoot,BstSpec,EqualSide};pub use node_id::{BstNodeId,BstNodeIdManager};pub use seeker::BstSeeker;pub use split::{Split,Split3};pub mod data{use super::{BstDataMutRef,BstSpec,LazyMapAct,LazyMapAgg,LazyMapMonoid,LazyMapMonoidWithKeyAct,Monoid,MonoidAct};use std::{fmt,fmt::Debug,mem::replace};pub trait BstDataAccess{type Value:?Sized;fn bst_data(&self)->&Self::Value;fn bst_data_mut(&mut self)->&mut Self::Value;}pub struct MonoidAggElementwhere M:Monoid{pub agg:M::T}implDebug for MonoidAggElementwhere M:Monoid{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{f.debug_struct("MonoidAggElement").field("agg",&self.agg).finish()}}implMonoidAggElementwhere M:Monoid{pub fn top_down(_node:BstDataMutRef<'_,Spec>)where Spec:BstSpec>{}pub fn bottom_up(mut node:BstDataMutRef<'_,Spec>)where Spec:BstSpec>{let mut agg=node.reborrow().into_data().bst_data().agg.clone();if let Ok(left)=node.reborrow().left().descend(){agg=M::operate(&left.into_data().bst_data().agg,&agg);}if let Ok(right)=node.reborrow().right().descend(){agg=M::operate(&agg,&right.into_data().bst_data().agg);}node.data_mut().bst_data_mut().agg=agg;}}pub struct MonoidActElementwhere M:MonoidAct{pub key:M::Key,pub act:M::Act}implDebug for MonoidActElementwhere M:MonoidAct{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{f.debug_struct("MonoidActElement").field("key",&self.key).field("act",&self.act).finish()}}implMonoidActElementwhere M:MonoidAct{pub fn from_key(key:M::Key)->Self{Self{key,act:M::unit()}}pub fn update_act(mut node:BstDataMutRef<'_,Spec>,act:&M::Act)where Spec:BstSpec>{M::operate_assign(&mut node.data_mut().bst_data_mut().act,act);M::act_assign(&mut node.data_mut().bst_data_mut().key,act);}pub fn top_down(mut node:BstDataMutRef<'_,Spec>)where Spec:BstSpec>{let act=replace(&mut node.data_mut().bst_data_mut().act,M::unit());if let Ok(left)=node.reborrow_datamut().left().descend(){Self::update_act(left,&act);}if let Ok(right)=node.reborrow_datamut().right().descend(){Self::update_act(right,&act);}}}pub struct LazyMapElementwhere L:LazyMapMonoid{pub key:L::Key,pub agg:LazyMapAgg,pub act:LazyMapAct}implDebug for LazyMapElementwhere L:LazyMapMonoid,LazyMapAgg:Debug,LazyMapAct:Debug{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{f.debug_struct("LazyMapElement").field("key",&self.key).field("agg",&self.agg).field("act",&self.act).finish()}}implLazyMapElementwhere L:LazyMapMonoid{pub fn from_key(key:L::Key)->Self{let agg=L::single_agg(&key);Self{key,agg,act:L::act_unit()}}pub fn update_act(mut node:BstDataMutRef<'_,Spec>,act:&LazyMapAct)where L:LazyMapMonoidWithKeyAct,Spec:BstSpec>{if L::is_act_unit(act){return;}L::act_operate_assign(&mut node.data_mut().bst_data_mut().act,act);node.data_mut().bst_data_mut().key=L::act_key(&node.reborrow().into_data().bst_data().key,act);if let Some(nxlazy)=L::act_agg(&node.reborrow().into_data().bst_data().agg,act){node.data_mut().bst_data_mut().agg=nxlazy;}else{Self::top_down(node.reborrow_datamut());Self::bottom_up(node.reborrow_datamut());}}pub fn top_down(mut node:BstDataMutRef<'_,Spec>)where L:LazyMapMonoidWithKeyAct,Spec:BstSpec>{if L::is_act_unit(&node.reborrow().into_data().bst_data().act){return;}let act=replace(&mut node.data_mut().bst_data_mut().act,L::act_unit());if let Ok(left)=node.reborrow_datamut().left().descend(){Self::update_act(left,&act);}if let Ok(right)=node.reborrow_datamut().right().descend(){Self::update_act(right,&act);}}pub fn bottom_up(mut node:BstDataMutRef<'_,Spec>)where Spec:BstSpec>{let mut agg=L::single_agg(&node.reborrow().into_data().bst_data().key);if let Ok(left)=node.reborrow().left().descend(){agg=L::agg_operate(&left.into_data().bst_data().agg,&agg);}if let Ok(right)=node.reborrow().right().descend(){agg=L::agg_operate(&agg,&right.into_data().bst_data().agg);}node.data_mut().bst_data_mut().agg=agg;}}pub mod marker{pub enum Key{}pub enum Size{}pub enum MonoidAgg{}pub enum MonoidAct{}pub enum LazyMap{}}}pub mod node{use super::{Allocator,BstSeeker};use std::{cmp::Ordering,marker::PhantomData,ptr::NonNull};#[derive(Clone,Copy,Debug,Eq,PartialEq)]pub enum EqualSide{Left,Right}impl EqualSide{pub fn goes_left(self,ordering:Ordering)->bool{match ordering{Ordering::Less=>true,Ordering::Equal=>matches!(self,Self::Left),Ordering::Greater=>false,}}}pub trait BstSpec:Sized{type Parent:ParentStrategy;type Data;fn top_down(_node:BstDataMutRef<'_,Self>){}fn bottom_up(_node:BstDataMutRef<'_,Self>){}fn merge(left:Option>,right:Option>)->Option>;fn split(node:Option>,seeker:Seeker,equal_side:EqualSide)->(Option>,Option>)where Seeker:BstSeeker;}pub struct BstNode>{pub data:Data,pub parent:Parent,pub child:[Option>>;2]}implBstNodewhere Parent:Default{pub fn new(data:Data)->Self{Self{data,parent:Parent::default(),child:[None,None]}}}pub trait ParentStrategy:Sized+Default{type Data;fn take_parent(_node:BstNodeRef,Spec>)where Spec:BstSpec{}fn set_parent(_node:BstNodeRef,Spec>,_parent:Option>>)where Spec:BstSpec{}}pub struct WithNoParent{_marker:PhantomDataData>}implDefault for WithNoParent{fn default()->Self{Self{_marker:PhantomData}}}implParentStrategy for WithNoParent{type Data=Data;fn take_parent(_node:BstNodeRef,Spec>)where Spec:BstSpec{}fn set_parent(_node:BstNodeRef,Spec>,_parent:Option>>)where Spec:BstSpec{}}pub struct WithParent{pub parent:Option>>}implDefault for WithParent{fn default()->Self{Self{parent:Default::default()}}}implParentStrategy for WithParent{type Data=Data;fn take_parent(mut node:BstNodeRef,Spec>)where Spec:BstSpec{unsafe{node.node.as_mut().parent=Default::default()};}fn set_parent(mut node:BstNodeRef,Spec>,parent:Option>>)where Spec:BstSpec{unsafe{node.node.as_mut().parent.parent=parent};}}implWithParent{pub fn resolve_top_down(node:BstNodeRef,Spec>)where Spec:BstSpec{unsafe{let(mut node,mut stack)=node.root_path();while let Some(is_left)=stack.pop(){Spec::top_down(node.reborrow_datamut());if is_left{node=node.left().descend().unwrap_unchecked();}else{node=node.right().descend().unwrap_unchecked();}}Spec::top_down(node.reborrow_datamut());}}pub fn resolve_bottom_up(mut node:BstNodeRef,Spec>)where Spec:BstSpec{loop{Spec::bottom_up(node.reborrow_datamut());match node.ascend(){Ok(parent)=>node=parent,Err(_)=>break,}}}pub fn is_root(node:BstNodeRef,Spec>)->bool where Spec:BstSpec{unsafe{node.node.as_ref().parent.parent.is_none()}}pub unsafe fn remove_root(root:&mut Option>)->Option>where Spec:BstSpec{let mut node=root.take()?;unsafe{let left=node.borrow_mut().left_mut().take();let right=node.borrow_mut().right_mut().take();*root=Spec::merge(left,right);Spec::bottom_up(node.borrow_datamut());Some(node)}}pub unsafe fn remove_not_root(mut node:BstNodeRef,Spec>)->BstNodeRefwhere Spec:BstSpec{assert!(!Self::is_root(node.reborrow()));unsafe{let left=node.left_mut().take();let right=node.right_mut().take();let merged=Spec::merge(left,right);let node_inner=node.node;let mut parent=node.ascend().unwrap_unchecked();let mut node=if let Some(merged)=merged{let node=if parent.reborrow().left().descend().is_ok_and(|n|n.node==node_inner){parent.left_mut().replace(merged)}else{parent.right_mut().replace(merged)};Self::resolve_bottom_up(parent.reborrow_datamut());node.unwrap_unchecked()}else{let node=if parent.reborrow().left().descend().is_ok_and(|n|n.node==node_inner){parent.left_mut().take()}else{parent.right_mut().take()};Self::resolve_bottom_up(parent.reborrow_datamut());node.unwrap_unchecked()};Spec::bottom_up(node.borrow_datamut());node}}}pub struct BstNodeRefwhere Spec:BstSpec{pub node:NonNull>,_marker:PhantomData}impl<'a,Spec>Copy for BstNodeRef,Spec>where Spec:BstSpec{}impl<'a,Spec>Clone for BstNodeRef,Spec>where Spec:BstSpec{fn clone(&self)->Self{*self}}implBstNodeRefwhere Spec:BstSpec,BorrowType:marker::BorrowType{#[doc=" # Safety"]#[doc=" The reachable nodes must form a valid tree and remain allocated while this"]#[doc=" handle or derived references are used. Ownership and aliases must match `BorrowType`."]pub unsafe fn new_unchecked(node:NonNull>)->Self{Self{node,_marker:PhantomData}}pub fn reborrow(&self)->BstNodeRef,Spec>{BstNodeRef{node:self.node,_marker:PhantomData}}pub fn left(self)->BstEdgeHandle{BstEdgeHandle{node:self,_marker:PhantomData}}pub fn right(self)->BstEdgeHandle{BstEdgeHandle{node:self,_marker:PhantomData}}}implBstNodeRefwhere Spec:BstSpec>,BorrowType:marker::BorrowType{pub fn ascend(self)->Result,Self>{const{assert!(BorrowType::TRAVERSAL_PERMIT);};let parent=unsafe{self.node.as_ref().parent.parent};parent.map(|node|BstNodeRef{node,_marker:PhantomData}).ok_or(self)}pub fn root_path(self)->(Self,Vec){let mut node=self;let mut nn=node.node;let mut stack=vec![];let root=loop{match node.ascend(){Ok(parent)=>{node=parent;stack.push(node.reborrow().left().descend().is_ok_and(|node|node.node==nn));nn=node.node;}Err(node)=>{break node;}}};(root,stack)}}implBstNodeRefwhere Spec:BstSpec{#[doc=" # Safety"]#[doc=" The allocator must keep this node alive until all handles and references"]#[doc=" to it have been discarded."]pub unsafe fn from_data(data:Spec::Data,allocator:&mut A)->Self where A:Allocator>{unsafe{Self::new_unchecked(allocator.allocate(BstNode::new(data)))}}pub fn borrow_mut(&mut self)->BstNodeRef,Spec>{BstNodeRef{node:self.node,_marker:PhantomData}}pub fn borrow_datamut(&mut self)->BstNodeRef,Spec>{BstNodeRef{node:self.node,_marker:PhantomData}}pub fn into_dying(self)->BstNodeRef{BstNodeRef{node:self.node,_marker:PhantomData}}}impl<'a,Spec>BstNodeRef,Spec>where Spec:BstSpec{pub fn into_data(self)->&'a Spec::Data{unsafe{&self.node.as_ref().data}}pub fn traverse(self,f:&mut F)where F:FnMut(Self){if let Ok(left)=self.left().descend(){left.traverse(f);}f(self);if let Ok(right)=self.right().descend(){right.traverse(f);}}pub fn leftmost(self)->Self{let mut node=self;while let Ok(left)=node.left().descend(){node=left;}node}pub fn rightmost(self)->Self{let mut node=self;while let Ok(right)=node.right().descend(){node=right;}node}}impl<'a,Spec>BstNodeRef,Spec>where Spec:BstSpec{pub fn reborrow_datamut(&mut self)->BstNodeRef,Spec>{BstNodeRef{node:self.node,_marker:PhantomData}}pub fn data_mut(&mut self)->&mut Spec::Data{unsafe{&mut self.node.as_mut().data}}pub fn swap_children(&mut self){unsafe{self.node.as_mut().child.swap(0,1)};}}impl<'a,Spec>BstNodeRef,Spec>where Spec:BstSpec{pub fn into_data_mut(mut self)->&'a mut Spec::Data{unsafe{&mut self.node.as_mut().data}}}impl<'a,Spec>BstNodeRef,Spec>where Spec:BstSpec{pub fn reborrow_datamut(&mut self)->BstNodeRef,Spec>{BstNodeRef{node:self.node,_marker:PhantomData}}pub fn left_mut(&mut self)->BstEdgeHandle,Spec>,marker::Left>{BstEdgeHandle{node:BstNodeRef{node:self.node,_marker:PhantomData},_marker:PhantomData}}pub fn right_mut(&mut self)->BstEdgeHandle,Spec>,marker::Right>{BstEdgeHandle{node:BstNodeRef{node:self.node,_marker:PhantomData},_marker:PhantomData}}}impl<'a,Spec>BstNodeRef,Spec>where Spec:BstSpec{pub fn dormant(self)->BstNodeRef{BstNodeRef{node:self.node,_marker:PhantomData}}}implBstNodeRefwhere Spec:BstSpec{pub unsafe fn awaken<'a>(self)->BstNodeRef,Spec>{BstNodeRef{node:self.node,_marker:PhantomData}}}implBstNodeRefwhere Spec:BstSpec{pub unsafe fn into_data(self,allocator:&mut A)->Spec::Data where A:Allocator>{debug_assert!(self.reborrow().left().descend().is_err());debug_assert!(self.reborrow().right().descend().is_err());unsafe{allocator.deallocate(self.node).data}}pub unsafe fn drop_all(self,allocator:&mut A)where A:Allocator>{let mut stack=vec![self.node];while let Some(node)=stack.pop(){stack.extend(unsafe{allocator.deallocate(node).child.into_iter().flatten()});}}}pub struct BstEdgeHandle{node:Node,_marker:PhantomData}implBstEdgeHandle,Dir>where Spec:BstSpec,BorrowType:marker::BorrowType,Dir:marker::BstDirection{pub fn descend(self)->Result,Self>{const{assert!(BorrowType::TRAVERSAL_PERMIT);};let child=unsafe{self.node.node.as_ref().child.get_unchecked(Dir::IDX)};child.map(|node|BstNodeRef{node,_marker:PhantomData}).ok_or(self)}}impl<'a,Spec,Dir>BstEdgeHandle,Spec>,Dir>where Spec:BstSpec,Dir:marker::BstDirection{pub unsafe fn take(&mut self)->Option>{let child=unsafe{self.node.node.as_mut().child.get_unchecked_mut(Dir::IDX)};child.take().map(|node|{let mut node=BstNodeRef{node,_marker:PhantomData};Spec::Parent::take_parent(node.borrow_mut());node})}pub unsafe fn replace(&mut self,mut other:BstNodeRef)->Option>{let child=unsafe{self.node.node.as_mut().child.get_unchecked_mut(Dir::IDX)};Spec::Parent::set_parent(other.borrow_mut(),Some(self.node.node));child.replace(other.node).map(|node|{let mut node=BstNodeRef{node,_marker:PhantomData};Spec::Parent::take_parent(node.borrow_mut());node})}pub unsafe fn set(&mut self,mut other:BstNodeRef){let child=unsafe{self.node.node.as_mut().child.get_unchecked_mut(Dir::IDX)};Spec::Parent::set_parent(other.borrow_mut(),Some(self.node.node));*child=Some(other.node);}}pub type BstRoot=BstNodeRef;pub type BstDataMutRef<'a,Spec>=BstNodeRef,Spec>;pub type BstImmutRef<'a,Spec>=BstNodeRef,Spec>;pub type BstNodePtr=NonNull>;pub mod marker{use std::marker::PhantomData;pub enum Left{}pub enum Right{}pub trait BstDirection{const IDX:usize;}impl BstDirection for Left{const IDX:usize=0;}impl BstDirection for Right{const IDX:usize=1;}pub enum Owned{}pub enum Dying{}pub enum DormantMut{}pub struct Immut<'a>(PhantomData<&'a()>);pub struct Mut<'a>(PhantomData<&'a mut()>);pub struct DataMut<'a>(PhantomData<&'a mut()>);pub trait BorrowType{const TRAVERSAL_PERMIT:bool=true;}impl BorrowType for Owned{const TRAVERSAL_PERMIT:bool=false;}impl BorrowType for Dying{}impl BorrowType for DormantMut{}impl<'a>BorrowType for Immut<'a>{}impl<'a>BorrowType for Mut<'a>{}impl<'a>BorrowType for DataMut<'a>{}}}pub mod node_id{use super::{BstNode,BstNodePtr,BstNodeRef,BstRoot,BstSpec,node};use std::{collections::{HashMap,hash_map::Entry},hash::{Hash,Hasher},ptr::NonNull,sync::atomic::{self,AtomicU64}};pub struct BstNodeIdwhere Spec:BstSpec{node:NonNull>,generation:u64}implClone for BstNodeIdwhere Spec:BstSpec{fn clone(&self)->Self{*self}}implCopy for BstNodeIdwhere Spec:BstSpec{}implPartialEq for BstNodeIdwhere Spec:BstSpec{fn eq(&self,other:&Self)->bool{self.node==other.node&&self.generation==other.generation}}implEq for BstNodeIdwhere Spec:BstSpec{}implHash for BstNodeIdwhere Spec:BstSpec{fn hash(&self,state:&mut H){self.node.hash(state);self.generation.hash(state);}}implBstNodeIdwhere Spec:BstSpec{pub unsafe fn reborrow<'a>(self,_root:&'a Option>)->BstNodeRef,Spec>{unsafe{BstNodeRef::new_unchecked(self.node)}}pub unsafe fn reborrow_datamut<'a>(self,_root:&'a mut Option>)->BstNodeRef,Spec>{unsafe{BstNodeRef::new_unchecked(self.node)}}pub unsafe fn reborrow_mut<'a>(self,_root:&'a mut Option>)->BstNodeRef,Spec>{unsafe{BstNodeRef::new_unchecked(self.node)}}}static GENERATION:AtomicU64=AtomicU64::new(0);pub struct BstNodeIdManagerwhere Spec:BstSpec{node_ids:HashMap,u64>}implDefault for BstNodeIdManagerwhere Spec:BstSpec{fn default()->Self{Self{node_ids:Default::default()}}}implBstNodeIdManagerwhere Spec:BstSpec{pub fn new()->Self{Self::default()}pub fn is_empty(&self)->bool{self.node_ids.is_empty()}pub fn len(&self)->usize{self.node_ids.len()}pub fn contains(&self,node_id:&BstNodeId)->bool{self.node_ids.get(&node_id.node).is_some_and(|&g|g==node_id.generation)}pub fn registered_node_id(&self,node:BstNodeRef,Spec>)->Option>{self.node_ids.get(&node.node).map(|&generation|BstNodeId{node:node.node,generation})}pub fn clear(&mut self){self.node_ids.clear();}pub fn register(&mut self,node:&BstRoot)->BstNodeId{let node_id=BstNodeId{node:node.node,generation:GENERATION.fetch_update(atomic::Ordering::Relaxed,atomic::Ordering::Relaxed,|x|{x.checked_add(1)}).expect("Generation counter overflow")};self.node_ids.insert(node_id.node,node_id.generation);node_id}pub fn unregister(&mut self,node_id:BstNodeId){match self.node_ids.entry(node_id.node){Entry::Occupied(entry)if*entry.get()==node_id.generation=>{entry.remove();}_=>{}}}}}pub mod seeker{use super::{BstDataAccess,BstImmutRef,BstSpec,LazyMapAgg,LazyMapMonoid,data,data::LazyMapElement};use std::{borrow::Borrow,cmp::Ordering,marker::PhantomData};pub trait BstSeeker{type Spec:BstSpec;fn bst_seek(&mut self,_node:BstImmutRef<'_,Self::Spec>)->Ordering;}pub struct SeekLeft{_marker:PhantomDataSpec>}implDefault for SeekLeft{fn default()->Self{Self{_marker:PhantomData}}}implBstSeeker for SeekLeftwhere Spec:BstSpec{type Spec=Spec;fn bst_seek(&mut self,node:BstImmutRef<'_,Self::Spec>)->Ordering{if node.reborrow().left().descend().is_ok(){Ordering::Greater}else{Ordering::Equal}}}pub struct SeekRight{_marker:PhantomDataSpec>}implDefault for SeekRight{fn default()->Self{Self{_marker:PhantomData}}}implBstSeeker for SeekRightwhere Spec:BstSpec{type Spec=Spec;fn bst_seek(&mut self,node:BstImmutRef<'_,Self::Spec>)->Ordering{if node.reborrow().right().descend().is_ok(){Ordering::Less}else{Ordering::Equal}}}pub struct SeekByKey<'a,Spec,K,Q>where Q:?Sized{key:&'a Q,_marker:PhantomData(Spec,K)>}impl<'a,Spec,K,Q>SeekByKey<'a,Spec,K,Q>where Q:?Sized{pub fn new(key:&'a Q)->Self{Self{key,_marker:PhantomData}}}implBstSeeker for SeekByKey<'_,Spec,K,Q>where Spec:BstSpec>,K:Borrow,Q:Ord+?Sized{type Spec=Spec;fn bst_seek(&mut self,node:BstImmutRef<'_,Self::Spec>)->Ordering{node.reborrow().into_data().bst_data().borrow().cmp(self.key)}}pub struct SeekBySize{index:usize,_marker:PhantomDataSpec>}implSeekBySize{pub fn new(index:usize)->Self{Self{index,_marker:PhantomData}}}implBstSeeker for SeekBySizewhere Spec:BstSpec>{type Spec=Spec;fn bst_seek(&mut self,node:BstImmutRef<'_,Self::Spec>)->Ordering{let lsize=node.reborrow().left().descend().map(|l|*l.into_data().bst_data()).unwrap_or_default();let ord=lsize.cmp(&self.index);if matches!(ord,Ordering::Less){self.index-=lsize+1;}ord}}pub struct SeekByAccCondwhere L:LazyMapMonoid{acc:LazyMapAgg,f:F,_marker:PhantomData(Spec,L)>}implSeekByAccCondwhere L:LazyMapMonoid,F:FnMut(&LazyMapAgg)->bool{pub fn new(f:F)->Self{Self{acc:L::agg_unit(),f,_marker:PhantomData}}}implBstSeeker for SeekByAccCondwhere Spec:BstSpec>>,L:LazyMapMonoid,F:FnMut(&LazyMapAgg)->bool{type Spec=Spec;fn bst_seek(&mut self,node:BstImmutRef<'_,Self::Spec>)->Ordering{if let Ok(left)=node.reborrow().left().descend(){let left_agg=&left.into_data().bst_data().agg;let nagg=L::agg_operate(&self.acc,left_agg);if(self.f)(&nagg){return Ordering::Greater;}let nagg=L::agg_operate(&nagg,&L::single_agg(&node.reborrow().into_data().bst_data().key));if(self.f)(&nagg){Ordering::Equal}else{self.acc=nagg;Ordering::Less}}else{let nagg=L::agg_operate(&self.acc,&L::single_agg(&node.reborrow().into_data().bst_data().key));if(self.f)(&nagg){Ordering::Equal}else{self.acc=nagg;Ordering::Less}}}}pub struct SeekByRaccCondwhere L:LazyMapMonoid{acc:LazyMapAgg,f:F,_marker:PhantomData(Spec,L)>}implSeekByRaccCondwhere L:LazyMapMonoid,F:FnMut(&LazyMapAgg)->bool{pub fn new(f:F)->Self{Self{acc:L::agg_unit(),f,_marker:PhantomData}}}implBstSeeker for SeekByRaccCondwhere Spec:BstSpec>>,L:LazyMapMonoid,F:FnMut(&LazyMapAgg)->bool{type Spec=Spec;fn bst_seek(&mut self,node:BstImmutRef<'_,Self::Spec>)->Ordering{if let Ok(right)=node.reborrow().right().descend(){let right_agg=&right.into_data().bst_data().agg;let nagg=L::agg_operate(right_agg,&self.acc);if(self.f)(&nagg){return Ordering::Less;}let nagg=L::agg_operate(&L::single_agg(&node.reborrow().into_data().bst_data().key),&nagg);if(self.f)(&nagg){Ordering::Equal}else{self.acc=nagg;Ordering::Greater}}else{let nagg=L::agg_operate(&L::single_agg(&node.reborrow().into_data().bst_data().key),&self.acc);if(self.f)(&nagg){Ordering::Equal}else{self.acc=nagg;Ordering::Greater}}}}}pub mod split{use super::{BstDataAccess,BstDataMutRef,BstImmutRef,BstRoot,BstSeeker,BstSpec,EqualSide,data::{self},seeker::{SeekByKey,SeekBySize}};use std::{borrow::Borrow,ops::{Bound,RangeBounds}};pub struct Split<'a,Spec>where Spec:BstSpec{left:Option>,right:Option>,root:&'a mut Option>}impl<'a,Spec>Split<'a,Spec>where Spec:BstSpec{pub fn new(node:&'a mut Option>,seeker:Seek,equal_side:EqualSide)->Self where Seek:BstSeeker{let(left,right)=Spec::split(node.take(),seeker,equal_side);Self{left,right,root:node}}pub fn left(&self)->Option>{self.left.as_ref().map(|node|node.reborrow())}pub fn right(&self)->Option>{self.right.as_ref().map(|node|node.reborrow())}pub fn left_datamut(&mut self)->Option>{self.left.as_mut().map(|node|node.borrow_datamut())}pub fn right_datamut(&mut self)->Option>{self.right.as_mut().map(|node|node.borrow_datamut())}pub fn manually_merge(&mut self,mut f:F)where F:FnMut(Option>,Option>)->Option>{self.left=f(self.left.take(),self.right.take());}}impl<'a,Spec>Drop for Split<'a,Spec>where Spec:BstSpec{fn drop(&mut self){*self.root=Spec::merge(self.left.take(),self.right.take());}}pub struct Split3<'a,Spec>where Spec:BstSpec{left:Option>,mid:Option>,right:Option>,root:&'a mut Option>}impl<'a,Spec>Split3<'a,Spec>where Spec:BstSpec{pub fn new(node:&'a mut Option>,start:Bound,end:Bound)->Self where Seek1:BstSeeker,Seek2:BstSeeker{let(mut rest,right)=match end{Bound::Included(seeker)=>Spec::split(node.take(),seeker,EqualSide::Left),Bound::Excluded(seeker)=>Spec::split(node.take(),seeker,EqualSide::Right),Bound::Unbounded=>(node.take(),None),};let(left,mid)=match start{Bound::Included(seeker)=>Spec::split(rest.take(),seeker,EqualSide::Right),Bound::Excluded(seeker)=>Spec::split(rest.take(),seeker,EqualSide::Left),Bound::Unbounded=>(None,rest),};Self{left,mid,right,root:node}}pub fn left(&self)->Option>{self.left.as_ref().map(|node|node.reborrow())}pub fn mid(&self)->Option>{self.mid.as_ref().map(|node|node.reborrow())}pub fn right(&self)->Option>{self.right.as_ref().map(|node|node.reborrow())}pub fn left_datamut(&mut self)->Option>{self.left.as_mut().map(|node|node.borrow_datamut())}pub fn mid_datamut(&mut self)->Option>{self.mid.as_mut().map(|node|node.borrow_datamut())}pub fn right_datamut(&mut self)->Option>{self.right.as_mut().map(|node|node.borrow_datamut())}pub fn split_mid(&mut self,seeker:Seek,equal_side:EqualSide)->Split<'_,Spec>where Seek:BstSeeker{Split::new(&mut self.mid,seeker,equal_side)}pub fn manually_merge(&mut self,mut f:F)where F:FnMut(Option>,Option>)->Option>{let rest=f(self.mid.take(),self.right.take());self.mid=f(self.left.take(),rest);}pub fn seek_by_key(node:&'a mut Option>,range:R)->Self where Spec:BstSpec>,K:Borrow,Q:Ord+?Sized,R:RangeBounds{let start=match range.start_bound(){Bound::Included(key)=>Bound::Included(SeekByKey::new(key)),Bound::Excluded(key)=>Bound::Excluded(SeekByKey::new(key)),Bound::Unbounded=>Bound::Unbounded,};let end=match range.end_bound(){Bound::Included(key)=>Bound::Included(SeekByKey::new(key)),Bound::Excluded(key)=>Bound::Excluded(SeekByKey::new(key)),Bound::Unbounded=>Bound::Unbounded,};Self::new(node,start,end)}pub fn seek_by_size(node:&'a mut Option>,range:R)->Self where Spec:BstSpec>,R:RangeBounds{let start=match range.start_bound(){Bound::Included(&index)=>Bound::Included(SeekBySize::new(index)),Bound::Excluded(&index)=>Bound::Excluded(SeekBySize::new(index)),Bound::Unbounded=>Bound::Unbounded,};let end=match range.end_bound(){Bound::Included(&index)=>Bound::Included(SeekBySize::new(index)),Bound::Excluded(&index)=>Bound::Excluded(SeekBySize::new(index)),Bound::Unbounded=>Bound::Unbounded,};Self::new(node,start,end)}}impl<'a,Spec>Drop for Split3<'a,Spec>where Spec:BstSpec{fn drop(&mut self){let rest=Spec::merge(self.mid.take(),self.right.take());*self.root=Spec::merge(self.left.take(),rest);}}}} // codesnip-guard: bounded #[cfg_attr(any(),rustfmt::skip)]pub use self::bounded::Bounded;#[cfg_attr(any(),rustfmt::skip)]mod bounded{#[doc=" Trait for max/min bounds"]pub trait Bounded:Sized+PartialOrd{fn maximum()->Self;fn minimum()->Self;fn is_maximum(&self)->bool{self==&Self::maximum()}fn is_minimum(&self)->bool{self==&Self::minimum()}fn set_maximum(&mut self){*self=Self::maximum()}fn set_minimum(&mut self){*self=Self::minimum()}}macro_rules!impl_bounded_num{($($t:ident)*)=>{$(impl Bounded for$t{fn maximum()->Self{$t::MAX}fn minimum()->Self{$t::MIN}})*};}impl_bounded_num!(u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize f32 f64);macro_rules!impl_bounded_tuple{(@impl$($T:ident)*)=>{impl<$($T:Bounded),*>Bounded for($($T,)*){fn maximum()->Self{($(<$T as Bounded>::maximum(),)*)}fn minimum()->Self{($(<$T as Bounded>::minimum(),)*)}}};(@inner$($T:ident)*,)=>{impl_bounded_tuple!(@impl$($T)*);};(@inner$($T:ident)*,$U:ident$($Rest:ident)*)=>{impl_bounded_tuple!(@impl$($T)*);impl_bounded_tuple!(@inner$($T)*$U,$($Rest)*);};($T:ident$($Rest:ident)*)=>{impl_bounded_tuple!(@inner$T,$($Rest)*);};}impl_bounded_tuple!(A B C D E F G H I J);impl Bounded for(){fn maximum()->Self{}fn minimum()->Self{}}impl Bounded for bool{fn maximum()->Self{true}fn minimum()->Self{false}}implBounded for Optionwhere T:Bounded{fn maximum()->Self{Some(::maximum())}fn minimum()->Self{None}}implBounded for std::cmp::Reversewhere T:Bounded{fn maximum()->Self{std::cmp::Reverse(::minimum())}fn minimum()->Self{std::cmp::Reverse(::maximum())}}} // codesnip-guard: zero_one #[cfg_attr(any(),rustfmt::skip)]pub use self::zero_one::{One,Zero};#[cfg_attr(any(),rustfmt::skip)]mod zero_one{pub trait Zero:Sized{fn zero()->Self;#[inline]fn is_zero(&self)->bool where Self:PartialEq{self==&Self::zero()}#[inline]fn set_zero(&mut self){*self=Self::zero();}}pub trait One:Sized{fn one()->Self;#[inline]fn is_one(&self)->bool where Self:PartialEq{self==&Self::one()}#[inline]fn set_one(&mut self){*self=Self::one();}}macro_rules!impl_zero_one{($({$(<$T:ident:$Bound:ident>)?$Trait:ident$method:ident$($t:ty)*,$e:expr})*)=>{$(impl_zero_one!(@impl[$(<$T:$Bound>)?]$Trait$method[$($t)*],$e);)*};(@impl[<$T:ident:$Bound:ident>]$Trait:ident$method:ident[$($t:ty)*],$e:expr)=>{$(impl<$T:$Bound>$Trait for$t{fn$method()->Self{$e}})*};(@impl[]$Trait:ident$method:ident[$($t:ty)*],$e:expr)=>{$(impl$Trait for$t{fn$method()->Self{$e}})*};}impl_zero_one!({Zero zero u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128,0}{Zero zero f32 f64,0.}{One one u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128,1}{One one f32 f64,1.}{Zero zero std::num::Wrapping,Self(T::zero())}{One one std::num::Wrapping,Self(T::one())});}