// codesnip-guard: Doubling #[cfg_attr(any(),rustfmt::skip)]pub use self::doubling::{Doubling,FunctionalGraphDoubling};#[cfg_attr(any(),rustfmt::skip)]mod doubling{use super::{Group,LevelAncestor,Monoid,UndirectedSparseGraph};use std::collections::VecDeque;pub struct Doublingwhere M:Monoid{size:usize,table:Vec<(usize,M::T)>}implDoublingwhere M:Monoid{pub fn new(size:usize,f:impl Fn(usize)->(usize,M::T))->Self{let mut table=Vec::with_capacity(size);for i in 0..size{table.push(f(i));}Self{size,table}}pub fn double(&mut self){let base=self.table.len()-self.size;for i in 0..self.size{let&(to,ref val)=&self.table[base+i];if to!=!0{let&(to2,ref val2)=&self.table[base+to];self.table.push((to2,M::operate(val,val2)));}else{self.table.push((!0,M::unit()));}}}pub fn kth(&mut self,mut pos:usize,mut k:usize)->(usize,M::T){let mut x=M::unit();for chunk in self.table.chunks_exact(self.size){if k&1==1{let&(to,ref val)=&chunk[pos];if to==!0{return(!0,M::unit());}x=M::operate(&x,val);pos=to;}k>>=1;if k==0{break;}}while k>0{self.double();if k&1==1{let base=self.table.len()-self.size;let&(to,ref val)=&self.table[base+pos];if to==!0{return(!0,M::unit());}x=M::operate(&x,val);pos=to;}k>>=1;}(pos,x)}#[doc=" queries: (pos, k)"]#[doc=" Return: (pos, acc)"]pub fn kth_multiple(&self,queries:impl IntoIterator)->Vec<(usize,M::T)>{let(mut ks,mut results):(Vec,Vec<(usize,M::T)>)=queries.into_iter().map(|(start,k)|(k,(start,M::unit()))).unzip();for chunk in self.table.chunks_exact(self.size){for(i,k)in ks.iter_mut().enumerate(){if*k&1==1{let&(to,ref val)=&chunk[results[i].0];if to==!0{results[i]=(!0,M::unit());*k=0;}else{results[i].1=M::operate(&results[i].1,val);results[i].0=to;}}*k>>=1;}}if ks.iter().any(|&k|k>0){let mut dp=self.table[self.table.len()-self.size..].to_vec();while ks.iter().any(|&k|k>0){let mut ndp=Vec::with_capacity(dp.len());for i in 0..self.size{let&(to,ref val)=&dp[i];if to!=!0{let&(to2,ref val2)=&dp[to];ndp.push((to2,M::operate(val,val2)));}else{ndp.push((!0,M::unit()));}}dp=ndp;for(i,k)in ks.iter_mut().enumerate(){if*k&1==1{let&(to,ref val)=&dp[results[i].0];if to==!0{results[i]=(!0,M::unit());*k=0;}else{results[i].1=M::operate(&results[i].1,val);results[i].0=to;}}*k>>=1;}}}results}#[doc=" Return: (k, (pos, acc))"]pub fn find_last(&self,mut pos:usize,mut pred:impl FnMut(usize,&M::T)->bool)->(usize,(usize,M::T)){let mut k=0usize;let mut x=M::unit();assert!(pred(pos,&x));for(i,chunk)in self.table.chunks_exact(self.size).enumerate().rev(){let&(to,ref val)=&chunk[pos];let nx=M::operate(&x,val);if pred(to,&nx){x=nx;pos=to;k|=1<bool)->Option<(usize,(usize,M::T))>{let(mut k,(mut pos,mut x))=self.find_last(pos,|k,x|!pred(k,x));k+=1;M::operate_assign(&mut x,&self.table[pos].1);pos=self.table[pos].0;if pred(pos,&x){Some((k,(pos,x)))}else{None}}}pub struct FunctionalGraphDoublingwhere M:Group{depth_to_cycle:Vec,cycle_entry:Vec,cycle_id:Vec,cycle_pos:Vec,cycles:Vec>,cycle_prefix:Vec>,prefix_up:Vec,la:LevelAncestor}implFunctionalGraphDoublingwhere M:Group{pub fn new(size:usize,f:impl Fn(usize)->(usize,M::T))->Self{let(next,value):(Vec<_>,Vec<_>)=(0..size).map(f).unzip();let mut indeg=vec![0usize;size];for&to in&next{indeg[to]+=1;}let mut in_cycle=vec![true;size];let mut deq=VecDeque::new();for(u,°)in indeg.iter().enumerate(){if deg==0{deq.push_back(u);}}while let Some(u)=deq.pop_front(){in_cycle[u]=false;indeg[next[u]]-=1;if indeg[next[u]]==0{deq.push_back(next[u]);}}let mut cycle_id=vec![!0;size];let mut cycle_pos=vec![!0;size];let mut cycles=Vec::new();for i in 0..size{if in_cycle[i]&&cycle_id[i]==!0{let mut cycle=Vec::new();let mut u=i;loop{cycle_id[u]=cycles.len();cycle_pos[u]=cycle.len();cycle.push(u);u=next[u];if u==i{break;}}cycles.push(cycle);}}let mut rev=vec![Vec::new();size];for u in 0..size{rev[next[u]].push(u);}let mut depth_to_cycle=vec![0usize;size];let mut cycle_entry=vec![!0;size];let mut prefix_up=Vec::with_capacity(size);prefix_up.resize_with(size,M::unit);let mut q=VecDeque::new();for i in 0..size{if in_cycle[i]{cycle_entry[i]=i;prefix_up[i]=M::operate(&value[i],&M::unit());q.push_back(i);}}while let Some(u)=q.pop_front(){for&v in&rev[u]{if in_cycle[v]||cycle_entry[v]!=!0{continue;}cycle_entry[v]=cycle_entry[u];depth_to_cycle[v]=depth_to_cycle[u]+1;cycle_id[v]=cycle_id[u];prefix_up[v]=M::operate(&value[v],&prefix_up[u]);q.push_back(v);}}let mut cycle_prefix=Vec::with_capacity(cycles.len());for cycle in&cycles{let len=cycle.len();let mut pref=Vec::with_capacity(2*len+1);pref.push(M::unit());for i in 0..2*len{let v=cycle[i%len];let next_val=M::operate(pref.last().unwrap(),&value[v]);pref.push(next_val);}cycle_prefix.push(pref);}let root=size;let mut edges=Vec::with_capacity(size);for u in 0..size{if in_cycle[u]{edges.push((u,root));}else{edges.push((u,next[u]));}}let graph=UndirectedSparseGraph::from_edges(size+1,edges);let la=graph.level_ancestor(root);Self{depth_to_cycle,cycle_entry,cycle_id,cycle_pos,cycles,cycle_prefix,prefix_up,la}}fn acc_to_ancestor(&self,u:usize,ancestor:usize)->M::T{let inv=M::inverse(&self.prefix_up[ancestor]);M::operate(&self.prefix_up[u],&inv)}fn cycle_segment(&self,cycle_id:usize,start:usize,len:usize)->M::T{if len==0{return M::unit();}let pref=&self.cycle_prefix[cycle_id];let inv=M::inverse(&pref[start]);M::operate(&inv,&pref[start+len])}fn cycle_acc_from(&self,entry:usize,steps:usize)->M::T{if steps==0{return M::unit();}let cycle_id=self.cycle_id[entry];let start=self.cycle_pos[entry];let len=self.cycles[cycle_id].len();let q=steps/len;let r=steps%len;let rem=self.cycle_segment(cycle_id,start,r);if q==0{return rem;}let full=self.cycle_segment(cycle_id,start,len);let pow=M::pow(full,q);M::operate(&pow,&rem)}fn cycle_jump_from(&self,entry:usize,steps:usize)->usize{if steps==0{return entry;}let cycle_id=self.cycle_id[entry];let start=self.cycle_pos[entry];let len=self.cycles[cycle_id].len();let idx=(start+steps%len)%len;self.cycles[cycle_id][idx]}pub fn kth(&self,u:usize,k:usize)->(usize,M::T){let depth=self.depth_to_cycle[u];if k<=depth{let ancestor=self.la.la(u,k).unwrap();let acc=self.acc_to_ancestor(u,ancestor);return(ancestor,acc);}let entry=self.cycle_entry[u];let acc_tree=self.acc_to_ancestor(u,entry);let steps=k-depth;let pos=self.cycle_jump_from(entry,steps);let acc_cycle=self.cycle_acc_from(entry,steps);let acc=M::operate(&acc_tree,&acc_cycle);(pos,acc)}#[doc=" queries: (pos, k)"]#[doc=" Return: (pos, acc)"]pub fn kth_multiple(&self,queries:impl IntoIterator)->Vec<(usize,M::T)>{queries.into_iter().map(|(u,k)|self.kth(u,k)).collect()}}} // codesnip-guard: Graph #[cfg_attr(any(),rustfmt::skip)]pub use self::graph_base::*;#[cfg_attr(any(),rustfmt::skip)]mod graph_base{#[doc=" A neighboring vertex and the label of the arc used to reach it."]#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash)]pub struct Neighbor{pub to:V,pub label:L}implNeighbor{#[inline]pub fn new(to:V,label:L)->Self{Self{to,label}}}implFrom<(V,L)>for Neighbor{#[inline]fn from((to,label):(V,L))->Self{Self::new(to,label)}}#[doc=" A finite graph whose outgoing arcs can be iterated without allocation."]pub trait Graph{type Vertex:Copy+Eq;type Label;type Vertices<'g>:Iteratorwhere Self:'g;type Neighbors<'g>:Iterator>where Self:'g;fn vsize(&self)->usize;fn vertices(&self)->Self::Vertices<'_>;fn neighbors(&self,vertex:Self::Vertex)->Self::Neighbors<'_>;}#[doc=" A graph whose adjacency relation represents directed arcs."]pub trait DirectedGraph:Graph{}pub trait VertexMap:Graph{type Vmap;fn construct_vmap(&self,f:F)->Self::Vmap where F:FnMut()->T;fn vmap_get<'a>(&self,map:&'a Self::Vmap,vertex:Self::Vertex)->&'a T;fn vmap_get_mut<'a>(&self,map:&'a mut Self::Vmap,vertex:Self::Vertex)->&'a mut T;#[inline]fn vmap_set(&self,map:&mut Self::Vmap,vertex:Self::Vertex,value:T){*self.vmap_get_mut(map,vertex)=value;}}pub trait EdgeMap:Graph{type Emap;fn construct_emap(&self,f:F)->Self::Emap where F:FnMut()->T;fn emap_get<'a>(&self,map:&'a Self::Emap,eid:Self::Label)->&'a T;fn emap_get_mut<'a>(&self,map:&'a mut Self::Emap,eid:Self::Label)->&'a mut T;#[inline]fn emap_set(&self,map:&mut Self::Emap,eid:Self::Label,value:T){*self.emap_get_mut(map,eid)=value;}}} // codesnip-guard: LevelAncestor #[cfg_attr(any(),rustfmt::skip)]pub use self::level_ancestor::LevelAncestor;#[cfg_attr(any(),rustfmt::skip)]mod level_ancestor{use super::UndirectedSparseGraph;pub struct LevelAncestor{parent:Vec,depth:Vec,start:Vec,index:Vec,ladder:Vec}impl UndirectedSparseGraph{pub fn level_ancestor(&self,root:usize)->LevelAncestor{let n=self.vertices_size();let(order,parent)=self.tree_order(root);let mut depth=vec![0;n];for&u in order.iter().skip(1){depth[u]=depth[parent[u]]+1;}let mut height=vec![1;n];let mut heavy=vec![n;n];for&u in order.iter().skip(1).rev(){let p=parent[u];if heavy[p]==n||height[heavy[p]])->Vec>{let n=self.vertices_size();let mut start=vec![0;n+1];let queries:Vec<(usize,usize)>=queries.into_iter().collect();for&(u,_)in&queries{start[u]+=1;}for d in 0..n{start[d+1]+=start[d];}let qsize=queries.len();let mut batch=vec![(0,0);qsize];for(i,&(u,k))in queries.iter().enumerate(){start[u]-=1;batch[start[u]]=(k,i);}let(order,parent)=self.tree_order(root);let mut path=Vec::with_capacity(n);let mut results=vec![None;qsize];for u in order{while path.last().is_some_and(|&v|v!=parent[u]){path.pop();}path.push(u);for&(k,qi)in&batch[start[u]..start[u+1]]{let depth=path.len()-1;if k<=depth{results[qi]=Some(path[depth-k]);}}}results}}impl LevelAncestor{#[inline]pub fn la(&self,mut u:usize,mut k:usize)->Option{if self.depth[u]usize{self.depth[u]}}} // codesnip-guard: SparseGraph #[cfg_attr(any(),rustfmt::skip)]pub use self::sparse_graph::*;#[cfg_attr(any(),rustfmt::skip)]mod sparse_graph{use super::{DirectedGraph,EdgeMap,Graph,MarkedScan,Neighbor,Scan,ScanSource,VertexMap};use std::{iter::Copied,marker::PhantomData,ops,slice};type Marker=PhantomDataT>;#[derive(Clone,Copy,Debug,Eq,PartialEq,Ord,PartialOrd,Hash)]pub enum DirectedEdge{}#[derive(Clone,Copy,Debug,Eq,PartialEq,Ord,PartialOrd,Hash)]pub enum UndirectedEdge{}#[derive(Clone,Copy,Debug,Eq,PartialEq,Ord,PartialOrd,Hash)]pub enum BidirectionalEdge{}#[doc=" Static Sparse Graph represented as Compressed Sparse Row."]#[derive(Debug,Clone)]pub struct SparseGraph{vsize:usize,start:Vec,neighbors:Vec>,pub edges:Vec<(usize,usize)>,_marker:Marker}implSparseGraph{#[doc=" Return the number of vertices."]#[inline]pub fn vertices_size(&self)->usize{self.vsize}#[doc=" Return the number of edges."]#[inline]pub fn edges_size(&self)->usize{self.edges.len()}#[doc=" Return an iterator over graph vertices."]#[inline]pub fn vertices(&self)->ops::Range{0..self.vertices_size()}pub fn builder(vsize:usize)->SparseGraphBuilder{SparseGraphBuilder::new(vsize)}pub fn builder_with_esize(vsize:usize,esize:usize)->SparseGraphBuilder{SparseGraphBuilder::new_with_esize(vsize,esize)}}pub trait SparseGraphConstruction:Sized{fn construct_graph(vsize:usize,edges:Vec<(usize,usize)>)->SparseGraph;}implSparseGraphwhere D:SparseGraphConstruction{#[doc=" Construct graph from edges."]pub fn from_edges(vsize:usize,edges:Vec<(usize,usize)>)->Self{D::construct_graph(vsize,edges)}pub fn reverse_graph(&self)->SparseGraph{let edges=self.edges.iter().map(|&(from,to)|(to,from)).collect();D::construct_graph(self.vsize,edges)}}impl SparseGraphConstruction for DirectedEdge{fn construct_graph(vsize:usize,edges:Vec<(usize,usize)>)->SparseGraph{let mut start:Vec<_>=vec![0usize;vsize+1];for(from,_)in edges.iter().cloned(){start[from]+=1;}for i in 1..=vsize{start[i]+=start[i-1];}let mut neighbors=Vec::>::with_capacity(edges.len());let ptr=neighbors.as_mut_ptr();for(id,(from,to))in edges.iter().cloned().enumerate(){start[from]-=1;unsafe{ptr.add(start[from]).write(Neighbor::new(to,id))};}unsafe{neighbors.set_len(edges.len())};SparseGraph{vsize,start,neighbors,edges,_marker:PhantomData}}}impl SparseGraphConstruction for UndirectedEdge{fn construct_graph(vsize:usize,edges:Vec<(usize,usize)>)->SparseGraph{let mut start:Vec<_>=vec![0usize;vsize+1];for(from,to)in edges.iter().cloned(){start[to]+=1;start[from]+=1;}for i in 1..=vsize{start[i]+=start[i-1];}let mut neighbors=Vec::>::with_capacity(edges.len()*2);let ptr=neighbors.as_mut_ptr();for(id,(from,to))in edges.iter().cloned().enumerate(){start[from]-=1;unsafe{ptr.add(start[from]).write(Neighbor::new(to,id))};start[to]-=1;unsafe{ptr.add(start[to]).write(Neighbor::new(from,id))};}unsafe{neighbors.set_len(edges.len()*2)};SparseGraph{vsize,start,neighbors,edges,_marker:PhantomData}}}impl SparseGraphConstruction for BidirectionalEdge{fn construct_graph(vsize:usize,edges:Vec<(usize,usize)>)->SparseGraph{let mut start:Vec<_>=vec![0usize;vsize+1];for(from,to)in edges.iter().cloned(){start[to]+=1;start[from]+=1;}for i in 1..=vsize{start[i]+=start[i-1];}let mut neighbors=Vec::>::with_capacity(edges.len()*2);let ptr=neighbors.as_mut_ptr();for(id,(from,to))in edges.iter().cloned().enumerate(){start[from]-=1;unsafe{ptr.add(start[from]).write(Neighbor::new(to,id*2))};start[to]-=1;unsafe{ptr.add(start[to]).write(Neighbor::new(from,id*2+1))};}unsafe{neighbors.set_len(edges.len()*2)};SparseGraph{vsize,start,neighbors,edges,_marker:PhantomData}}}pub type DirectedSparseGraph=SparseGraph;pub type UndirectedSparseGraph=SparseGraph;pub type BidirectionalSparseGraph=SparseGraph;pub struct SparseGraphBuilder{vsize:usize,edges:Vec<(usize,usize)>,rest:Vec,_marker:Marker}implSparseGraphBuilder{pub fn new(vsize:usize)->Self{Self{vsize,edges:Default::default(),rest:Default::default(),_marker:PhantomData}}pub fn new_with_esize(vsize:usize,esize:usize)->Self{Self{vsize,edges:Vec::with_capacity(esize),rest:Vec::with_capacity(esize),_marker:PhantomData}}pub fn add_edge(&mut self,u:usize,v:usize,w:T){self.edges.push((u,v));self.rest.push(w);}}implSparseGraphBuilderwhere D:SparseGraphConstruction{pub fn build(self)->(SparseGraph,Vec){let graph=SparseGraph::from_edges(self.vsize,self.edges);(graph,self.rest)}}pub struct SparseGraphScannerwhere U:Scan,T:Scan{vsize:usize,esize:usize,_marker:Marker<(U,T,D)>}implSparseGraphScannerwhere U:Scan,T:Scan{pub fn new(vsize:usize,esize:usize)->Self{Self{vsize,esize,_marker:PhantomData}}}implMarkedScan for SparseGraphScannerwhere U:Scan,T:Scan,D:SparseGraphConstruction{type Output=(SparseGraph,Vec<::Output>);fn mscan(self,iter:&mut I)->Option{let mut builder=SparseGraphBuilder::new_with_esize(self.vsize,self.esize);for _ in 0..self.esize{builder.add_edge(U::scan(iter)?,U::scan(iter)?,T::scan(iter)?);}Some(builder.build())}}pub type DirectedGraphScanner=SparseGraphScanner;pub type UndirectedGraphScanner=SparseGraphScanner;pub type BidirectionalGraphScanner=SparseGraphScanner;pub struct TreeGraphScannerwhere U:Scan,T:Scan{vsize:usize,_marker:Marker<(U,T)>}implTreeGraphScannerwhere U:Scan,T:Scan{pub fn new(vsize:usize)->Self{Self{vsize,_marker:PhantomData}}}implMarkedScan for TreeGraphScannerwhere U:Scan,T:Scan{type Output=(UndirectedSparseGraph,Vec<::Output>);fn mscan(self,iter:&mut I)->Option{UndirectedGraphScanner::::new(self.vsize,self.vsize-1).mscan(iter)}}implGraph for SparseGraphwhere D:SparseGraphConstruction{type Vertex=usize;type Label=usize;type Vertices<'g>=ops::Rangewhere D:'g;type Neighbors<'g>=Copied>>where D:'g;#[inline]fn vsize(&self)->usize{self.vsize}#[inline]fn vertices(&self)->Self::Vertices<'_>{0..self.vsize}#[inline]fn neighbors(&self,vertex:Self::Vertex)->Self::Neighbors<'_>{self.neighbors[self.start[vertex]..self.start[vertex+1]].iter().copied()}}impl DirectedGraph for SparseGraph{}implEdgeMapfor SparseGraph{type Emap=Vec;#[inline]fn construct_emap(&self,f:F)->Self::Emap where F:FnMut()->T{let mut map=Vec::with_capacity(self.edges.len());map.resize_with(self.edges.len(),f);map}#[inline]fn emap_get<'a>(&self,map:&'a Self::Emap,eid:Self::Label)->&'a T{&map[eid]}#[inline]fn emap_get_mut<'a>(&self,map:&'a mut Self::Emap,eid:Self::Label)->&'a mut T{&mut map[eid]}}implEdgeMapfor SparseGraph{type Emap=Vec;#[inline]fn construct_emap(&self,f:F)->Self::Emap where F:FnMut()->T{let mut map=Vec::with_capacity(self.edges.len());map.resize_with(self.edges.len(),f);map}#[inline]fn emap_get<'a>(&self,map:&'a Self::Emap,eid:Self::Label)->&'a T{&map[eid]}#[inline]fn emap_get_mut<'a>(&self,map:&'a mut Self::Emap,eid:Self::Label)->&'a mut T{&mut map[eid]}}implVertexMapfor SparseGraphwhere D:SparseGraphConstruction{type Vmap=Vec;#[inline]fn construct_vmap(&self,f:F)->Self::Vmap where F:FnMut()->T{let mut v=Vec::with_capacity(self.vsize);v.resize_with(self.vsize,f);v}#[inline]fn vmap_get<'a>(&self,map:&'a Self::Vmap,vid:Self::Vertex)->&'a T{&map[vid]}#[inline]fn vmap_get_mut<'a>(&self,map:&'a mut Self::Vmap,vid:Self::Vertex)->&'a mut T{&mut map[vid]}}} // 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: scanner #[cfg_attr(any(),rustfmt::skip)]pub use self::scanner::*;#[cfg_attr(any(),rustfmt::skip)]mod scanner{use std::{iter::{FromIterator,from_fn,repeat_with},marker::PhantomData};pub fn read_stdin_all()->String{use std::io::Read as _;let mut s=String::new();std::io::stdin().read_to_string(&mut s).expect("io error");s}pub fn read_stdin_all_unchecked()->String{use std::io::Read as _;let mut buf=Vec::new();std::io::stdin().read_to_end(&mut buf).expect("io error");unsafe{String::from_utf8_unchecked(buf)}}pub fn read_all(mut reader:impl std::io::Read)->String{let mut s=String::new();reader.read_to_string(&mut s).expect("io error");s}pub fn read_all_unchecked(mut reader:impl std::io::Read)->String{let mut buf=Vec::new();reader.read_to_end(&mut buf).expect("io error");unsafe{String::from_utf8_unchecked(buf)}}pub fn read_stdin_line()->String{let mut s=String::new();std::io::stdin().read_line(&mut s).expect("io error");s}pub trait Scan:Sized{type Output;fn scan(source:&mut S)->Option;fn scan_vec(source:&mut S,size:usize,capacity:usize)->Vec{let mut values=Vec::with_capacity(capacity.max(size));values.extend((0..size).map(|_|source.scan::()));values}}pub trait MarkedScan:Sized{type Output;fn mscan(self,source:&mut S)->Option;}pub trait ScanSource:Sized{#[doc=" Reads a token under the source's input requirements."]#[doc=" Checked sources return `None` at EOF; unchecked sources require available input."]fn next_token(&mut self)->Option<&str>;#[doc=" Skips separators without consuming the next token."]#[inline]fn skip_whitespace(&mut self){}#[inline]fn read_u8(&mut self)->Option{self.next_token()?.parse().ok()}#[inline]fn read_u16(&mut self)->Option{self.next_token()?.parse().ok()}#[inline]fn read_u32(&mut self)->Option{self.next_token()?.parse().ok()}fn read_u32_vec(&mut self,size:usize,capacity:usize)->Vec{let mut values=Vec::with_capacity(capacity.max(size));values.extend((0..size).map(|_|self.scan::()));values}#[inline]fn read_u64(&mut self)->Option{self.next_token()?.parse().ok()}#[inline]fn read_u128(&mut self)->Option{self.next_token()?.parse().ok()}#[inline]fn read_usize(&mut self)->Option{self.next_token()?.parse().ok()}#[inline]fn read_i8(&mut self)->Option{self.next_token()?.parse().ok()}#[inline]fn read_i16(&mut self)->Option{self.next_token()?.parse().ok()}#[inline]fn read_i32(&mut self)->Option{self.next_token()?.parse().ok()}#[inline]fn read_i64(&mut self)->Option{self.next_token()?.parse().ok()}#[inline]fn read_i128(&mut self)->Option{self.next_token()?.parse().ok()}#[inline]fn read_isize(&mut self)->Option{self.next_token()?.parse().ok()}#[doc=" Panics if reading fails."]#[inline]fn scan(&mut self)->T::Output{T::scan(self).expect("scan error")}#[doc=" Panics if reading fails."]#[inline]fn mscan(&mut self,marker:T)->T::Output{marker.mscan(self).expect("scan error")}fn scan_vec(&mut self,size:usize,capacity:usize)->Vec{if size==0{self.skip_whitespace();}T::scan_vec(self,size,capacity)}#[inline]fn iter(&mut self)->ScannerIter<'_,Self,T>{ScannerIter{inner:self,_marker:PhantomData}}}#[derive(Clone,Debug)]pub struct Scanner<'a,I:Iterator=std::str::SplitAsciiWhitespace<'a>>{iter:I}impl<'a>Scanner<'a>{pub fn new(s:&'a str)->Self{Self{iter:s.split_ascii_whitespace()}}}impl<'a,I:Iterator>Scanner<'a,I>{pub fn new_from_iter(iter:I)->Self{Self{iter}}}impl<'a,I:Iterator>ScanSource for Scanner<'a,I>{fn next_token(&mut self)->Option<&str>{self.iter.next()}}macro_rules!impl_scan{($($t:ty)*)=>{$(impl Scan for$t{type Output=Self;fn scan(iter:&mut I)->Option{iter.next_token()?.parse::<$t>().ok()}})*};}impl_scan!(char f32 f64 String);macro_rules!impl_integer_scan{($($t:ty=>$read:ident),*$(,)?)=>{$(impl Scan for$t{type Output=Self;#[inline]fn scan(source:&mut S)->Option{source.$read()}})*};}impl_integer_scan!(u8=>read_u8,u16=>read_u16,u64=>read_u64,u128=>read_u128,usize=>read_usize,i8=>read_i8,i16=>read_i16,i32=>read_i32,i64=>read_i64,i128=>read_i128,isize=>read_isize,);impl Scan for u32{type Output=Self;#[inline]fn scan(source:&mut S)->Option{source.read_u32()}fn scan_vec(source:&mut S,size:usize,capacity:usize)->Vec{source.read_u32_vec(size,capacity)}}macro_rules!impl_scan_tuple{(@impl$($T:ident)*)=>{impl<$($T:Scan),*>Scan for($($T,)*){type Output=($(<$T as Scan>::Output,)*);fn scan(_iter:&mut It)->Option{Some(($(<$T as Scan>::scan(_iter)?,)*))}}};(@inner$($T:ident)*,)=>{impl_scan_tuple!(@impl$($T)*);};(@inner$($T:ident)*,$U:ident$($Rest:ident)*)=>{impl_scan_tuple!(@impl$($T)*);impl_scan_tuple!(@inner$($T)*$U,$($Rest)*);};($($T:ident)*)=>{impl_scan_tuple!(@inner,$($T)*);};}impl_scan_tuple!(A B C D E F G H I J K);pub struct ScannerIter<'a,S,T>{inner:&'a mut S,_marker:PhantomDataT>}implIterator for ScannerIter<'_,S,T>{type Item=T::Output;#[inline]fn next(&mut self)->Option{T::scan(self.inner)}}#[doc=" scan a value with Scanner"]#[doc=""]#[doc=" - `scan_value!(scanner, ELEMENT)`"]#[doc=""]#[doc=" ELEMENT :="]#[doc=" - `$ty`: Scan"]#[doc=" - `&str`: borrowed token; the source stays borrowed until its last use"]#[doc=" - `@$expr`: MarkedScan"]#[doc=" - `$ty = $expr`: MarkedScan"]#[doc=" - `[ELEMENT; $expr]`: vector"]#[doc=" - `[$ty; $len; capacity $capacity]`: vector with reserved capacity"]#[doc=" - `[ELEMENT; const $expr]`: array"]#[doc=" - `[ELEMENT]`: iterator"]#[doc=" - `[ELEMENT; iter $expr]`: iterator of the specified length"]#[doc=" - `($(ELEMENT)*,)`: tuple"]#[macro_export]macro_rules!scan_value{(@repeat$scanner:expr,[$($t:tt)*]$len:expr)=>{{$crate::scan_value!(@iter$scanner,[$($t)*]$len).collect::>()}};(@repeat$scanner:expr,[$($t:tt)*])=>{{::std::iter::repeat_with(||$crate::scan_value!(@inner$scanner,[]$($t)*))}};(@iter$scanner:expr,[$($t:tt)*]$len:expr)=>{{let size=$len;if size==0{$scanner.skip_whitespace();}$crate::scan_value!(@repeat$scanner,[$($t)*]).take(size)}};(@array$scanner:expr,[$($t:tt)*]$len:expr)=>{{if$len==0{$scanner.skip_whitespace();}$crate::array![||$crate::scan_value!(@inner$scanner,[]$($t)*);$len]}};(@tuple$scanner:expr,[$([$($args:tt)*])*])=>{($($($args)*,)*)};(@sparen$scanner:expr,[]@$e:expr;$($t:tt)*)=>{$crate::scan_value!(@sparen$scanner,[@$e]$($t)*)};(@sparen$scanner:expr,[]($($tt:tt)*);$($t:tt)*)=>{$crate::scan_value!(@sparen$scanner,[($($tt)*)]$($t)*)};(@sparen$scanner:expr,[][$($tt:tt)*];$($t:tt)*)=>{$crate::scan_value!(@sparen$scanner,[[$($tt)*]]$($t)*)};(@sparen$scanner:expr,[]$ty:ty=$e:expr;$($t:tt)*)=>{$crate::scan_value!(@sparen$scanner,[$ty=$e]$($t)*)};(@sparen$scanner:expr,[]$ty:ty;$($t:tt)*)=>{$crate::scan_value!(@sparen$scanner,[$ty]$($t)*)};(@sparen$scanner:expr,[]$($args:tt)*)=>{$crate::scan_value!(@repeat$scanner,[$($args)*])};(@sparen$scanner:expr,[$($args:tt)+]const$len:expr)=>{$crate::scan_value!(@array$scanner,[$($args)+]$len)};(@sparen$scanner:expr,[$($args:tt)+]iter$len:expr)=>{$crate::scan_value!(@iter$scanner,[$($args)+]$len)};(@sparen$scanner:expr,[$($args:tt)+]$len:expr;capacity$capacity:expr)=>{{let size=$len;let capacity=$capacity;$scanner.scan_vec::<$($args)+>(size,capacity)}};(@sparen$scanner:expr,[$($args:tt)+]$len:expr)=>{$crate::scan_value!(@repeat$scanner,[$($args)+]$len)};(@$tag:ident$scanner:expr,[[$($args:tt)*]])=>{$($args)*};(@$tag:ident$scanner:expr,[$($args:tt)*]@$e:expr$(,$($t:tt)*)?)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$scanner.mscan($e)]]$(,$($t)*)?)};(@$tag:ident$scanner:expr,[$($args:tt)*]($($tuple:tt)*)$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@tuple$scanner,[]$($tuple)*)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][$($tt:tt)*]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@sparen$scanner,[]$($tt)*)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*]&str$(,$($t:tt)*)?)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$scanner.next_token().expect("scan error")]]$(,$($t)*)?)};(@$tag:ident$scanner:expr,[$($args:tt)*]$ty:ty=$e:expr$(,$($t:tt)*)?)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[{let _tmp:$ty=$scanner.mscan($e);_tmp}]]$(,$($t)*)?)};(@$tag:ident$scanner:expr,[$($args:tt)*]$ty:ty$(,$($t:tt)*)?)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$scanner.scan::<$ty>()]]$(,$($t)*)?)};(@$tag:ident$scanner:expr,[$($args:tt)*],$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*])=>{::std::compile_error!(::std::stringify!($($args)*))};(src=$src:expr,$($t:tt)*)=>{{let mut __scanner=Scanner::new($src);$crate::scan_value!(@inner __scanner,[]$($t)*)}};(iter=$iter:expr,$($t:tt)*)=>{{let mut __scanner=Scanner::new_from_iter($iter);$crate::scan_value!(@inner __scanner,[]$($t)*)}};($scanner:expr,$($t:tt)*)=>{$crate::scan_value!(@inner$scanner,[]$($t)*)}}#[doc=" scan and bind values with Scanner"]#[doc=""]#[doc=" - `scan!(scanner, $($pat $(: ELEMENT)?),*)`"]#[macro_export]macro_rules!scan{(@assert$p:pat)=>{};(@assert$($p:tt)*)=>{::std::compile_error!(::std::concat!("expected pattern, found `",::std::stringify!($($p)*),"`"));};(@pat$scanner:expr,[][])=>{};(@pat$scanner:expr,[][],$($t:tt)*)=>{$crate::scan!(@pat$scanner,[][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]$x:ident$($t:tt)*)=>{$crate::scan!(@pat$scanner,[$($p)*$x][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]::$($t:tt)*)=>{$crate::scan!(@pat$scanner,[$($p)*::][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]&$($t:tt)*)=>{$crate::scan!(@pat$scanner,[$($p)*&][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]($($x:tt)*)$($t:tt)*)=>{$crate::scan!(@pat$scanner,[$($p)*($($x)*)][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][][$($x:tt)*]$($t:tt)*)=>{$crate::scan!(@pat$scanner,[$($p)*[$($x)*]][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]{$($x:tt)*}$($t:tt)*)=>{$crate::scan!(@pat$scanner,[$($p)*{$($x)*}][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]:$($t:tt)*)=>{$crate::scan!(@ty$scanner,[$($p)*][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]$($t:tt)*)=>{$crate::scan!(@let$scanner,[$($p)*][usize]$($t)*)};(@ty$scanner:expr,[$($p:tt)*][$($tt:tt)*]@$e:expr$(,$($t:tt)*)?)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*@$e]$(,$($t)*)?)};(@ty$scanner:expr,[$($p:tt)*][$($tt:tt)*]($($x:tt)*)$($t:tt)*)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*($($x)*)]$($t)*)};(@ty$scanner:expr,[$($p:tt)*][$($tt:tt)*][$($x:tt)*]$($t:tt)*)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*[$($x)*]]$($t)*)};(@ty$scanner:expr,[$($p:tt)*][$($tt:tt)*]&str$(,$($t:tt)*)?)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*&str]$(,$($t)*)?)};(@ty$scanner:expr,[$($p:tt)*][$($tt:tt)*]$ty:ty=$e:expr$(,$($t:tt)*)?)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*$ty=$e]$(,$($t)*)?)};(@ty$scanner:expr,[$($p:tt)*][$($tt:tt)*]$ty:ty$(,$($t:tt)*)?)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*$ty]$(,$($t)*)?)};(@let$scanner:expr,[$($p:tt)*][$($tt:tt)*]$($t:tt)*)=>{$crate::scan!{@assert$($p)*}let$($p)* =$crate::scan_value!($scanner,$($tt)*);$crate::scan!(@pat$scanner,[][]$($t)*)};(src=$src:expr,$($t:tt)*)=>{let mut __scanner=Scanner::new($src);$crate::scan!(@pat __scanner,[][]$($t)*)};(iter=$iter:expr,$($t:tt)*)=>{let mut __scanner=Scanner::new_from_iter($iter);$crate::scan!(@pat __scanner,[][]$($t)*)};($scanner:expr,$($t:tt)*)=>{$crate::scan!(@pat$scanner,[][]$($t)*)}}#[doc=" define enum scan rules"]#[doc=""]#[doc=" # Example"]#[doc=" ```rust"]#[doc=" # use competitive::{define_enum_scan, tools::{CharsWithBase, Scan, ScanSource, Scanner, Usize1}};"]#[doc=" define_enum_scan! {"]#[doc=" enum Query: u8 {"]#[doc=" 0 => Noop,"]#[doc=" 1 => Args { i: Usize1, s: char },"]#[doc=" 9 => Complex { n: usize, c: [(usize, Vec = CharsWithBase('a')); n] },"]#[doc=" }"]#[doc=" }"]#[doc=" ```"]#[macro_export]macro_rules!define_enum_scan{(@field_ty@repeat[$($t:tt)*]$($len:expr)?)=>{Vec<$crate::define_enum_scan!(@field_ty$($t)*)>};(@field_ty@array[$($t:tt)*]$len:expr)=>{[$crate::define_enum_scan!(@field_ty$($t)*);$len]};(@field_ty@tuple[$([$($args:tt)*])*])=>{($($($args)*,)*)};(@field_ty@sparen[]($($tt:tt)*);$($t:tt)*)=>{$crate::define_enum_scan!(@field_ty@sparen[($($tt)*)]$($t)*)};(@field_ty@sparen[][$($tt:tt)*];$($t:tt)*)=>{$crate::define_enum_scan!(@field_ty@sparen[[$($tt)*]]$($t)*)};(@field_ty@sparen[]$ty:ty=$e:expr;$($t:tt)*)=>{$crate::define_enum_scan!(@field_ty@sparen[$ty=$e]$($t)*)};(@field_ty@sparen[]$ty:ty;$($t:tt)*)=>{$crate::define_enum_scan!(@field_ty@sparen[$ty]$($t)*)};(@field_ty@sparen[]$($args:tt)*)=>{$crate::define_enum_scan!(@field_ty@repeat[$($args)*])};(@field_ty@sparen[$($args:tt)+]const$len:expr)=>{$crate::define_enum_scan!(@field_ty@array[$($args)+]$len)};(@field_ty@sparen[$($args:tt)+]$len:expr)=>{$crate::define_enum_scan!(@field_ty@repeat[$($args)+]$len)};(@field_ty@$tag:ident[$($args:tt)*]($($tuple:tt)*)$($t:tt)*)=>{$crate::define_enum_scan!(@field_ty@$tag[$($args)*[$crate::define_enum_scan!(@field_ty@tuple[]$($tuple)*)]]$($t)*)};(@field_ty@$tag:ident[$($args:tt)*][$($tt:tt)*]$($t:tt)*)=>{$crate::define_enum_scan!(@field_ty@$tag[$($args)*[$crate::define_enum_scan!(@field_ty@sparen[]$($tt)*)]]$($t)*)};(@field_ty@$tag:ident[$($args:tt)*]$ty:ty=$e:expr$(,$($t:tt)*)?)=>{$crate::define_enum_scan!(@field_ty@$tag[$($args)*[$ty]]$(,$($t)*)?)};(@field_ty@$tag:ident[$($args:tt)*]$ty:ty$(,$($t:tt)*)?)=>{$crate::define_enum_scan!(@field_ty@$tag[$($args)*[<$ty as Scan>::Output]]$(,$($t)*)?)};(@field_ty@$tag:ident[$($args:tt)*],$($t:tt)*)=>{$crate::define_enum_scan!(@field_ty@$tag[$($args)*]$($t)*)};(@field_ty@$tag:ident[[$($args:tt)*]])=>{$($args)*};(@field_ty@$tag:ident[$($args:tt)*])=>{::std::compile_error!(::std::stringify!($($args)*))};(@field_ty$($t:tt)*)=>{$crate::define_enum_scan!(@field_ty@inner[]$($t)*)};(@tag_expr raw,$iter:ident)=>{ScanSource::next_token($iter)?};(@tag_expr$d:ty,$iter:ident)=>{<$d as Scan>::scan($iter)?};(@variant([$($attr:tt)*]$vis:vis$T:ident$d:tt)[$($vars:tt)*])=>{$crate::define_enum_scan!{@def$($attr)*$vis enum$T:$d{$($vars)*}}};(@variant$ctx:tt[$($vars:tt)*]$p:pat=>$v:ident{$($fs:tt)*}$($rest:tt)*)=>{$crate::define_enum_scan!{@field$ctx[$($vars)*]$p=>$v[]$($fs)*;$($rest)*}};(@variant$ctx:tt[$($vars:tt)*]$p:pat=>$v:ident$($rest:tt)*)=>{$crate::define_enum_scan!{@variant$ctx[$($vars)*$p=>$v,]$($rest)*}};(@variant$ctx:tt[$($vars:tt)*],$($rest:tt)*)=>{$crate::define_enum_scan!{@variant$ctx[$($vars)*]$($rest)*}};(@endfield$ctx:tt[$($vars:tt)*]$p:pat=>$v:ident[$($fs:tt)*][$f:ident:$($spec:tt)*],$($rest:tt)*)=>{$crate::define_enum_scan!{@field$ctx[$($vars)*]$p=>$v[$($fs)*[$f:$($spec)*]]$($rest)*}};(@endfield$ctx:tt[$($vars:tt)*]$p:pat=>$v:ident[$($fs:tt)*][$f:ident:$($spec:tt)*];$($rest:tt)*)=>{$crate::define_enum_scan!{@variant$ctx[$($vars)*$p=>$v{$($fs)*[$f:$($spec)*]},]$($rest)*}};(@field$ctx:tt[$($vars:tt)*]$p:pat=>$v:ident[$($fs:tt)*];$($rest:tt)*)=>{$crate::define_enum_scan!{@variant$ctx[$($vars)*$p=>$v{$($fs)*},]$($rest)*}};(@field$ctx:tt[$($vars:tt)*]$p:pat=>$v:ident[$($fs:tt)*]$f:ident:($($tuple:tt)*)$sep:tt$($rest:tt)*)=>{$crate::define_enum_scan!{@endfield$ctx[$($vars)*]$p=>$v[$($fs)*][$f:($($tuple)*)]$sep$($rest)*}};(@field$ctx:tt[$($vars:tt)*]$p:pat=>$v:ident[$($fs:tt)*]$f:ident:[$($x:tt)*]$sep:tt$($rest:tt)*)=>{$crate::define_enum_scan!{@endfield$ctx[$($vars)*]$p=>$v[$($fs)*][$f:[$($x)*]]$sep$($rest)*}};(@field$ctx:tt[$($vars:tt)*]$p:pat=>$v:ident[$($fs:tt)*]$f:ident:$ty:ty=$e:expr,$($rest:tt)*)=>{$crate::define_enum_scan!{@endfield$ctx[$($vars)*]$p=>$v[$($fs)*][$f:$ty=$e],$($rest)*}};(@field$ctx:tt[$($vars:tt)*]$p:pat=>$v:ident[$($fs:tt)*]$f:ident:$ty:ty;$($rest:tt)*)=>{$crate::define_enum_scan!{@endfield$ctx[$($vars)*]$p=>$v[$($fs)*][$f:$ty];$($rest)*}};(@field$ctx:tt[$($vars:tt)*]$p:pat=>$v:ident[$($fs:tt)*]$f:ident:$ty:ty=$e:expr;$($rest:tt)*)=>{$crate::define_enum_scan!{@endfield$ctx[$($vars)*]$p=>$v[$($fs)*][$f:$ty=$e];$($rest)*}};(@field$ctx:tt[$($vars:tt)*]$p:pat=>$v:ident[$($fs:tt)*]$f:ident:$ty:ty,$($rest:tt)*)=>{$crate::define_enum_scan!{@endfield$ctx[$($vars)*]$p=>$v[$($fs)*][$f:$ty],$($rest)*}};(@def$(#[$attr:meta])*$vis:vis enum$T:ident:$d:tt{$($p:pat=>$v:ident$({$([$f:ident:$($spec:tt)*])*})?,)*})=>{$(#[$attr])*$vis enum$T{$($v$({$($f:$crate::define_enum_scan!(@field_ty$($spec)*)),*})?),*}impl Scan for$T{type Output=Self;fn scan(iter:&mut I)->Option{let tag=$crate::define_enum_scan!(@tag_expr$d,iter);match tag{$($p=>{$($(let$f=$crate::scan_value!((*iter),$($spec)*);)*)?Some($T::$v$({$($f),*})?)}),*_=>None,}}}};($(#[$attr:meta])*$vis:vis enum$T:ident:raw{$($body:tt)*})=>{$crate::define_enum_scan!{@variant([$(#[$attr])*]$vis$T raw)[]$($body)*}};($(#[$attr:meta])*$vis:vis enum$T:ident:$d:ty{$($body:tt)*})=>{$crate::define_enum_scan!{@variant([$(#[$attr])*]$vis$T$d)[]$($body)*}};}#[derive(Debug,Copy,Clone)]pub enum Usize1{}impl Scan for Usize1{type Output=usize;fn scan(iter:&mut I)->Option{::scan(iter)?.checked_sub(1)}}#[derive(Debug,Copy,Clone)]pub struct CharWithBase(pub char);impl MarkedScan for CharWithBase{type Output=usize;fn mscan(self,iter:&mut I)->Option{Some((::scan(iter)?as u8-self.0 as u8)as usize)}}#[derive(Debug,Copy,Clone)]pub enum Chars{}impl Scan for Chars{type Output=Vec;fn scan(iter:&mut I)->Option{Some(iter.next_token()?.chars().collect())}}#[derive(Debug,Copy,Clone)]pub struct CharsWithBase(pub char);impl MarkedScan for CharsWithBase{type Output=Vec;fn mscan(self,iter:&mut I)->Option{Some(iter.next_token()?.chars().map(|c|(c as u8-self.0 as u8)as usize).collect())}}#[derive(Debug,Copy,Clone)]pub enum Byte1{}impl Scan for Byte1{type Output=u8;fn scan(iter:&mut I)->Option{let bytes=iter.next_token()?.as_bytes();assert_eq!(bytes.len(),1);Some(bytes[0])}}#[derive(Debug,Copy,Clone)]pub struct ByteWithBase(pub u8);impl MarkedScan for ByteWithBase{type Output=usize;fn mscan(self,iter:&mut I)->Option{Some((::scan(iter)?as u8-self.0)as usize)}}#[derive(Debug,Copy,Clone)]pub enum Bytes{}impl Scan for Bytes{type Output=Vec;fn scan(iter:&mut I)->Option{Some(iter.next_token()?.bytes().collect())}}#[derive(Debug,Copy,Clone)]pub struct BytesWithBase(pub u8);impl MarkedScan for BytesWithBase{type Output=Vec;fn mscan(self,iter:&mut I)->Option{Some(iter.next_token()?.bytes().map(|c|(c-self.0)as usize).collect())}}#[derive(Debug,Copy,Clone)]pub struct Collect::Output>>where T:Scan,B:FromIterator<::Output>{size:usize,_marker:PhantomData(T,B)>}implCollectwhere T:Scan,B:FromIterator<::Output>{pub fn new(size:usize)->Self{Self{size,_marker:PhantomData}}}implMarkedScan for Collectwhere T:Scan,B:FromIterator<::Output>{type Output=B;fn mscan(self,iter:&mut I)->Option{if self.size==0{iter.skip_whitespace();}repeat_with(| |::scan(iter)).take(self.size).collect()}}#[derive(Debug,Copy,Clone)]pub struct SizedCollect::Output>>where T:Scan,B:FromIterator<::Output>{_marker:PhantomData(T,B)>}implScan for SizedCollectwhere T:Scan,B:FromIterator<::Output>{type Output=B;fn scan(iter:&mut I)->Option{let size=usize::scan(iter)?;if size==0{iter.skip_whitespace();}repeat_with(| |::scan(iter)).take(size).collect()}}#[derive(Debug,Copy,Clone)]pub struct Splittedwhere T:Scan{pat:P,_marker:PhantomDataT>}implSplittedwhere T:Scan{pub fn new(pat:P)->Self{Self{pat,_marker:PhantomData}}}implMarkedScan for Splittedwhere T:Scan{type Output=Vec<::Output>;fn mscan(self,iter:&mut I)->Option{let mut iter=Scanner::new_from_iter(iter.next_token()?.split(self.pat));Some(from_fn(| |::scan(&mut iter)).collect())}}implMarkedScan for Splittedwhere T:Scan{type Output=Vec<::Output>;fn mscan(self,iter:&mut I)->Option{let mut iter=Scanner::new_from_iter(iter.next_token()?.split(self.pat));Some(from_fn(| |::scan(&mut iter)).collect())}}implMarkedScan for F where F:Fn(&str)->Option{type Output=T;fn mscan(self,iter:&mut I)->Option{self(iter.next_token()?)}}} // codesnip-guard: tree_order #[cfg_attr(any(),rustfmt::skip)]implSparseGraphwhere D:SparseGraphConstruction{#[doc=" (order, parents)"]pub fn tree_order(&self,root:usize)->(Vec,Vec){let n=self.vertices_size();let mut order=Vec::with_capacity(n);let mut parents=vec![!0usize;n];let mut stack=Vec::with_capacity(n);stack.push(root);while let Some(u)=stack.pop(){order.push(u);for a in self.neighbors(u).rev(){if a.to!=parents[u]{parents[a.to]=u;stack.push(a.to);}}}(order,parents)}}