// codesnip-guard: TransitionTable #[cfg_attr(any(),rustfmt::skip)]pub use self::transition_table::{SuffixCounts,TransitionTable};#[cfg_attr(any(),rustfmt::skip)]mod transition_table{use super::{Matrix,One,Saturating,SemiRing,StationaryTransducer,Transducer,Unsigned,Zero};#[doc=" Inputs are digits in `0..radix`; state ID 0 is the initial state."]#[derive(Debug,Clone)]pub struct TransitionTable{radix:usize,states:Vec,accepting:Vec,transitions:Vec>}implTransitionTable{pub fn new(machine:&T,radix:usize,max_states:usize)->Self where T:StationaryTransducer+?Sized,S:Eq+std::hash::Hash+Clone{assert!(max_states>0);let initial=machine.start();let mut states=vec![initial.clone()];let mut ids=std::collections::HashMap::from([(initial,0)]);let mut accepting=Vec::new();let mut transitions=Vec::new();let mut state=0;while stateusize{self.radix}pub fn state_size(&self)->usize{self.states.len()}#[doc=" Original states in ID order."]pub fn states(&self)->&[S]{&self.states}#[doc=" Indexed by input digit; each edge is `(next state ID, output)`."]pub fn transitions(&self,state:usize)->&[Option<(usize,O)>]{&self.transitions[state*self.radix..(state+1)*self.radix]}pub fn is_accepting(&self,state:usize)->bool{self.accepting[state]}}implStationaryTransducer for TransitionTablewhere O:Clone{}implTransducer for TransitionTablewhere O:Clone{type Input=usize;type Output=O;type State=usize;fn start(&self)->Self::State{0}fn relation(&self,state:&usize,input:&usize)->Option<(usize,O)>{self.transitions(*state).get(*input)?.clone()}fn accept(&self,state:&usize)->bool{self.is_accepting(*state)}}implTransitionTable{#[doc=" Entry `(from, to)` sums `weight(output)`, called once per edge."]pub fn to_matrix(&self,mut weight:impl FnMut(&O)->R::T)->Matrixwhere R:SemiRing{let size=self.state_size();let mut matrix=Matrix::zeros((size,size));for state in 0..size{for(next,output)in self.transitions(state).iter().flatten(){R::add_assign(&mut matrix[(state,*next)],&weight(output));}}matrix}}#[doc=" Counts accepted words, including leading zeros. Bound queries use the"]#[doc=" bound's length, digits in `0..radix`, and at most the precomputed length."]#[derive(Debug)]pub struct SuffixCounts<'a,V,S,O>{table:&'a TransitionTable,counts:Vec>}implClone for SuffixCounts<'_,V,S,O>where V:Clone{fn clone(&self)->Self{Self{table:self.table,counts:self.counts.clone()}}}implTransitionTable{#[doc=" Precomputes lengths `0..=len` in O(len * states * radix) time."]pub fn suffix_counts(&self,len:usize)->SuffixCounts<'_,V,S,O>where V:Clone+Zero+One+std::ops::Add{let mut counts=Vec::with_capacity(len+1);counts.push((0..self.state_size()).map(|state|{if self.is_accepting(state){V::one()}else{V::zero()}}).collect::>());for remaining in 0..len{let next=(0..self.state_size()).map(|state|{self.transitions(state).iter().flatten().fold(V::zero(),|sum,&(next,_)|{sum+counts[remaining][next].clone()})}).collect();counts.push(next);}SuffixCounts{table:self,counts}}}implSuffixCounts<'_,V,S,O>{#[doc=" Number of accepting continuations of `len` digits from `state`."]pub fn count(&self,state:usize,len:usize)->&V{&self.counts[len][state]}}implSuffixCounts<'_,V,S,O>where V:Clone+Zero+std::ops::Add{pub fn count_lt(&self,bound:&[usize])->V{self.count_bound::(0,bound,false)}pub fn count_le(&self,bound:&[usize])->V{self.count_bound::(0,bound,true)}#[doc=" Counts the inclusive interval `[lower, upper]` with equal-length bounds."]pub fn count_between(&self,lower:&[usize],upper:&[usize])->V{assert_eq!(lower.len(),upper.len());if lower>upper{return V::zero();}assert!(lower.len()state=*next,None=>return V::zero(),}continue;}let mut sum=V::zero();for(digit,edge)in edges.iter().enumerate().take(hi+1).skip(lo){if let Some((next,_))=edge{let count=if digit==lo{self.count_bound::(*next,&lower[i+1..],true)}else if digit==hi{self.count_bound::(*next,&upper[i+1..],true)}else{self.count(*next,lower.len()-i-1).clone()};sum=sum+count;}}return sum;}self.count(state,0).clone()}}implSuffixCounts<'_,Saturating,S,O>where U:Unsigned{#[doc=" The zero-based `k`th accepted word in lexicographic order, or `None` if absent."]#[doc=" Requires `k < U::MAX` because counts may saturate."]pub fn kth(&self,len:usize,mut k:U)->Option>{assert!(kOption>where Saturating:std::ops::Add>{assert!(kupper{return None;}let lower_counts=self.bound_counts::(lower);let upper_counts=self.bound_counts::(upper);let mut state=0;let(mut tight_lower,mut tight_upper)=(true,true);let mut word=Vec::with_capacity(lower.len());for i in 0..lower.len(){let edges=self.table.transitions(state);let lo=if tight_lower{lower[i]}else{0};let hi=if tight_upper{upper[i]}else{self.table.radix()-1};if tight_lower&&tight_upper&&lo==hi{state=edges[lo].as_ref()?.0;word.push(lo);continue;}let mut selected=None;for(digit,edge)in edges.iter().enumerate().take(hi+1).skip(lo){if let Some((next,_))=edge{let count=if tight_lower&&digit==lo{lower_counts[i+1].0}else if tight_upper&&digit==hi{upper_counts[i+1].0}else{self.count(*next,lower.len()-i-1).0};if count<=k{k-=count;}else{selected=Some((digit,*next));break;}}}let(digit,next)=selected?;tight_lower&=digit==lower[i];tight_upper&=digit==upper[i];word.push(digit);state=next;}(k.is_zero()&&self.table.is_accepting(state)).then_some(word)}}implSuffixCounts<'_,V,S,O>where V:Clone+Zero+std::ops::Add{fn count_bound(&self,mut state:usize,bound:&[usize],inclusive:bool)->V{assert!(bound.len()state=*next,None=>return sum,}}if inclusive{sum=sum+self.count(state,0).clone();}sum}fn bound_counts(&self,bound:&[usize])->Vec{assert!(bound.len()where 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: Matrix #[cfg_attr(any(),rustfmt::skip)]pub use self::matrix::Matrix;#[cfg_attr(any(),rustfmt::skip)]mod matrix{use super::{Field,Invertible,Ring,SemiRing};use std::{fmt::{self,Debug},marker::PhantomData,ops::{Add,AddAssign,Index,IndexMut,Mul,MulAssign,Neg,Sub,SubAssign}};pub struct Matrixwhere R:SemiRing{pub shape:(usize,usize),pub data:Vec>,_marker:PhantomDataR>}implDebug for Matrixwhere R:SemiRing{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{f.debug_struct("Matrix").field("shape",&self.shape).field("data",&self.data).field("_marker",&self._marker).finish()}}implClone for Matrixwhere R:SemiRing{fn clone(&self)->Self{Self{shape:self.shape,data:self.data.clone(),_marker:self._marker}}}implPartialEq for Matrixwhere R:SemiRing{fn eq(&self,other:&Self)->bool{self.shape==other.shape&&self.data==other.data}}implEq for Matrixwhere R:SemiRing{}implMatrixwhere R:SemiRing{pub fn new(shape:(usize,usize),z:R::T)->Self{Self{shape,data:vec![vec![z;shape.1];shape.0],_marker:PhantomData}}pub fn from_vec(data:Vec>)->Self{let shape=(data.len(),data.first().map(Vec::len).unwrap_or_default());assert!(data.iter().all(|r|r.len()==shape.1));Self{shape,data,_marker:PhantomData}}pub fn new_with(shape:(usize,usize),mut f:impl FnMut(usize,usize)->R::T)->Self{let data=(0..shape.0).map(|i|(0..shape.1).map(|j|f(i,j)).collect()).collect();Self{shape,data,_marker:PhantomData}}pub fn zeros(shape:(usize,usize))->Self{Self{shape,data:vec![vec![R::zero();shape.1];shape.0],_marker:PhantomData}}pub fn eye(shape:(usize,usize))->Self{let mut data=vec![vec![R::zero();shape.1];shape.0];for(i,d)in data.iter_mut().enumerate().take(shape.1){d[i]=R::one();}Self{shape,data,_marker:PhantomData}}pub fn transpose(&self)->Self{Self::new_with((self.shape.1,self.shape.0),|i,j|self[j][i].clone())}pub fn map(&self,mut f:F)->Matrixwhere S:SemiRing,F:FnMut(&R::T)->S::T{Matrix::::new_with(self.shape,|i,j|f(&self[i][j]))}pub fn add_row_with(&mut self,mut f:impl FnMut(usize,usize)->R::T){self.data.push((0..self.shape.1).map(|j|f(self.shape.0,j)).collect());self.shape.0+=1;}pub fn add_col_with(&mut self,mut f:impl FnMut(usize,usize)->R::T){for i in 0..self.shape.0{self.data[i].push(f(i,self.shape.1));}self.shape.1+=1;}pub fn pairwise_assign(&mut self,other:&Self,mut f:F)where F:FnMut(&mut R::T,&R::T){assert_eq!(self.shape,other.shape);for i in 0..self.shape.0{for j in 0..self.shape.1{f(&mut self[i][j],&other[i][j]);}}}}#[derive(Debug)]pub struct SystemOfLinearEquationsSolutionwhere R:Field{pub particular:Vec,pub basis:Vec>}implMatrixwhere R:Field{fn eliminate(&mut self)->(usize,R::T){let(n,m)=self.shape;let mut rank=0;let mut determinant=R::one();let mut negative=false;for first in(0..m).step_by(64){if rank==n{break;}let end=(first+64).min(m);let start=rank;let mut pivots=Vec::new();let mut panel=vec![vec![R::zero();end-first];end-first];for col in first..end{if panel[col-first][..col-first].iter().any(|x|!R::is_zero(x)){for row in&mut self.data[rank..]{let value=R::dot_product(&row[first..col],&panel[col-first][..col-first]);R::sub_assign(&mut row[col],&value);}}let Some(pivot)=(rank..n).find(|&i|!R::is_zero(&self[i][col]))else{continue;};if pivot!=rank{self.data.swap(rank,pivot);negative=!negative;}if DETERMINANT{R::mul_assign(&mut determinant,&self[rank][col]);}let inv=R::inv(&self[rank][col]);let row=&mut self.data[rank];for c in col+1..end{let value=R::dot_product(&row[first..col],&panel[c-first][..col-first]);R::sub_assign(&mut row[c],&value);panel[c-first][col-first]=row[c].clone();}for row in&mut self.data[rank+1..]{R::mul_assign(&mut row[col],&inv);}pivots.push(col);rank+=1;if rank==n{break;}}for i in start..if rank-start<32{n}else{rank}{let(upper,lower)=self.data.split_at_mut(i);let row=&mut lower[0];for(j,&col)in pivots[..(i-start).min(pivots.len())].iter().enumerate(){if R::is_zero(&row[col]){continue;}let factor=R::neg(&row[col]);R::add_scaled_assign(&mut row[end..],&upper[start+j][end..],&factor);}}if rank=32&&self.data[rank..].iter().any(|row|pivots.iter().any(|&col|!R::is_zero(&row[col]))){let lower=Self::new_with((n-rank,rank-start),|i,j|{R::neg(&self[rank+i][pivots[j]])});let upper=Self::new_with((rank-start,m-end),|i,j|{self[start+i][end+j].clone()});let update=&lower*&upper;for(row,update)in self.data[rank..].iter_mut().zip(update.data){for(x,y)in row[end..].iter_mut().zip(update){R::add_assign(x,&y);}}}for(i,&col)in pivots.iter().enumerate(){for row in&mut self.data[start+i+1..]{row[col]=R::zero();}}if DETERMINANT&&rank(&mut self,normalize:bool,mut f:F)where F:FnMut(usize,usize,usize){let(n,m)=self.shape;let mut c=0;for r in 0..n{loop{if c>=m{return;}if let Some(pivot)=(r..n).find(|&p|!R::is_zero(&self[p][c])){f(r,pivot,c);self.data.swap(r,pivot);break;};c+=1;}let d=R::inv(&self[r][c]);if normalize{for value in&mut self[r][c..m]{R::mul_assign(value,&d);}}for i in(0..n).filter(|&i|i!=r){let mut e=self[i][c].clone();if!normalize{R::mul_assign(&mut e,&d);}for j in c..m{let e=R::mul(&e,&self[r][j]);R::sub_assign(&mut self[i][j],&e);}}c+=1;}}pub fn row_reduction(&mut self,normalize:bool){self.row_reduction_with(normalize,|_,_,_|{});}pub fn rank(&mut self)->usize{self.eliminate::().0}pub fn determinant(&mut self)->R::T{assert_eq!(self.shape.0,self.shape.1);self.eliminate::().1}pub fn solve_system_of_linear_equations(&self,b:&[R::T])->Option>{assert_eq!(self.shape.0,b.len());let m=self.shape.1;let mut a=Self::new_with((self.shape.0,m+1),|i,j|{if j==m{b[i].clone()}else{self[i][j].clone()}});let rank=a.eliminate::().0;let mut pivots=Vec::with_capacity(rank);let mut b=Vec::with_capacity(rank);for row in&a.data[..rank]{let c=row.iter().position(|x|!R::is_zero(x)).unwrap();if c==m{return None;}pivots.push(c);b.push(row[m].clone());}let mut free=Vec::with_capacity(m-rank);let mut pivot=0;for c in 0..m{if pivot>=(0..rank).map(|i|free.iter().map(|&c|a[i][c].clone()).collect()).collect();for k in(0..rank).rev(){let c=pivots[k];let inv=R::inv(&a[k][c]);R::mul_assign(&mut b[k],&inv);let pivot_b=b[k].clone();let(upper,lower)=coefficients.split_at_mut(k);let pivot_coefficients=&mut lower[0];for x in pivot_coefficients.iter_mut(){R::mul_assign(x,&inv);}for((row,value),coefficients)in a.data[..k].iter_mut().zip(&mut b[..k]).zip(upper){if R::is_zero(&row[c]){continue;}let factor=row[c].clone();row[c]=R::zero();R::sub_assign(value,&R::mul(&factor,&pivot_b));R::add_scaled_assign(coefficients,pivot_coefficients,&R::neg(&factor));}}let mut particular=vec![R::zero();m];for i in 0..rank{particular[pivots[i]]=b[i].clone();}let mut basis=Vec::with_capacity(free.len());for(j,&c)in free.iter().enumerate(){let mut vector=vec![R::zero();m];vector[c]=R::one();for i in 0..rank{vector[pivots[i]]=R::neg(&coefficients[i][j]);}basis.push(vector);}Some(SystemOfLinearEquationsSolution{particular,basis})}pub fn inverse(&self)->Option>{assert_eq!(self.shape.0,self.shape.1);let n=self.shape.0;if n>=64{let m=n/2;let a=Self::new_with((m,m),|i,j|self[i][j].clone());if let Some(mut ai)=a.inverse(){let b=Self::new_with((m,n-m),|i,j|self[i][j+m].clone());let c=Self::new_with((n-m,m),|i,j|self[i+m][j].clone());let mut d=Self::new_with((n-m,n-m),|i,j|self[i+m][j+m].clone());let u=&ai*&b;let v=&c*&ai;d-=&v*&b;let di=d.inverse()?;let r=&u*&di;let t=&di*&v;ai+=&r*&v;let mut inverse=Self::zeros((n,n));for i in 0..m{inverse[i][..m].clone_from_slice(&ai[i]);for(x,y)in inverse[i][m..].iter_mut().zip(&r[i]){*x=R::neg(y);}}for i in m..n{for(x,y)in inverse[i][..m].iter_mut().zip(&t[i-m]){*x=R::neg(y);}inverse[i][m..].clone_from_slice(&di[i-m]);}return Some(inverse);}}let mut a=self.clone();let mut inverse=Self::eye((n,n));let mut ranges:Vec<_>=(0..n).map(|i|(i,i+1)).collect();for r in 0..n{let pivot=(r..n).find(|&i|!R::is_zero(&a[i][r]))?;a.data.swap(r,pivot);inverse.data.swap(r,pivot);ranges.swap(r,pivot);let d=R::inv(&a[r][r]);for x in&mut a[r][r..]{R::mul_assign(x,&d);}let(left,right)=ranges[r];for x in&mut inverse[r][left..right]{R::mul_assign(x,&d);}let(a_upper,a_lower)=a.data.split_at_mut(r+1);let pivot_a=&a_upper[r];let(inverse_upper,inverse_lower)=inverse.data.split_at_mut(r+1);let pivot_inverse=&inverse_upper[r];let(ranges_upper,ranges_lower)=ranges.split_at_mut(r+1);let(left,right)=ranges_upper[r];for((a,inverse),range)in a_lower.iter_mut().zip(inverse_lower).zip(ranges_lower){if R::is_zero(&a[r]){continue;}let e=a[r].clone();a[r]=R::zero();R::add_scaled_assign(&mut a[(r+1)..],&pivot_a[(r+1)..],&R::neg(&e));R::add_scaled_assign(&mut inverse[left..right],&pivot_inverse[left..right],&R::neg(&e));range.0=range.0 .min(left);range.1=range.1 .max(right);}}for r in(0..n).rev(){let(left,right)=ranges[r];let(inverse_upper,inverse_lower)=inverse.data.split_at_mut(r);let pivot_inverse=&inverse_lower[0];let(ranges_upper,_)=ranges.split_at_mut(r);for((a,inverse),range)in a.data[..r].iter_mut().zip(inverse_upper).zip(ranges_upper){if R::is_zero(&a[r]){continue;}let e=a[r].clone();a[r]=R::zero();R::add_scaled_assign(&mut inverse[left..right],&pivot_inverse[left..right],&R::neg(&e));range.0=range.0 .min(left);range.1=range.1 .max(right);}}Some(inverse)}pub fn characteristic_polynomial(&mut self)->Vec{let n=self.shape.0;if n==0{return vec![R::one()];}assert!(self.data.iter().all(|a|a.len()==n));for j in 0..(n-1){if let Some(x)=((j+1)..n).find(|&x|!R::is_zero(&self[x][j])){self.data.swap(j+1,x);self.data.iter_mut().for_each(|a|a.swap(j+1,x));let inv=R::inv(&self[j+1][j]);let mut v=vec![];let src=std::mem::take(&mut self[j+1]);for a in self.data[(j+2)..].iter_mut(){let mul=R::mul(&a[j],&inv);R::add_scaled_assign(&mut a[j..],&src[j..],&R::neg(&mul));v.push(mul);}self[j+1]=src;for a in self.data.iter_mut(){let v=R::dot_product(&a[(j+2)..],&v);R::add_assign(&mut a[j+1],&v);}}}let mut dp:Vec>=(0..=n).map(|i|Vec::with_capacity(n+1-i)).collect();dp[0].push(R::one());for i in 0..n{let mut c=vec![R::zero();i+1];c[i]=R::neg(&self[i][i]);let mut mul=R::one();for j in(0..i).rev(){mul=R::mul(&mul,&self[j+1][j]);c[j]=R::neg(&R::mul(&mul,&self[j][i]));}for k in(0..=i).rev(){let mut value=R::dot_product(&dp[k],&c[k..]);if k>0{R::add_assign(&mut value,dp[k-1].last().unwrap());}dp[k].push(value);}dp[i+1].push(R::one());}dp.into_iter().map(|mut c|c.pop().unwrap()).collect()}}implIndexfor Matrixwhere R:SemiRing{type Output=Vec;fn index(&self,index:usize)->&Self::Output{&self.data[index]}}implIndexMutfor Matrixwhere R:SemiRing{fn index_mut(&mut self,index:usize)->&mut Self::Output{&mut self.data[index]}}implIndex<(usize,usize)>for Matrixwhere R:SemiRing{type Output=R::T;fn index(&self,index:(usize,usize))->&Self::Output{&self.data[index.0][index.1]}}implIndexMut<(usize,usize)>for Matrixwhere R:SemiRing{fn index_mut(&mut self,index:(usize,usize))->&mut Self::Output{&mut self.data[index.0][index.1]}}macro_rules!impl_matrix_pairwise_binop{($imp:ident,$method:ident,$imp_assign:ident,$method_assign:ident$(where[$($clauses:tt)*])?)=>{impl$imp_assign for Matrixwhere R:SemiRing,$($($clauses)*)?{fn$method_assign(&mut self,rhs:Self){self.pairwise_assign(&rhs,|a,b|R::$method_assign(a,b));}}impl$imp_assign<&Matrix>for Matrixwhere R:SemiRing,$($($clauses)*)?{fn$method_assign(&mut self,rhs:&Self){self.pairwise_assign(rhs,|a,b|R::$method_assign(a,b));}}impl$imp for Matrixwhere R:SemiRing,$($($clauses)*)?{type Output=Matrix;fn$method(mut self,rhs:Self)->Self::Output{self.$method_assign(rhs);self}}impl$imp<&Matrix>for Matrixwhere R:SemiRing,$($($clauses)*)?{type Output=Matrix;fn$method(mut self,rhs:&Self)->Self::Output{self.$method_assign(rhs);self}}impl$imp>for&Matrixwhere R:SemiRing,$($($clauses)*)?{type Output=Matrix;fn$method(self,mut rhs:Matrix)->Self::Output{rhs.pairwise_assign(self,|a,b|*a=R::$method(b,a));rhs}}impl$imp<&Matrix>for&Matrixwhere R:SemiRing,$($($clauses)*)?{type Output=Matrix;fn$method(self,rhs:&Matrix)->Self::Output{let mut this=self.clone();this.$method_assign(rhs);this}}};}impl_matrix_pairwise_binop!(Add,add,AddAssign,add_assign);impl_matrix_pairwise_binop!(Sub,sub,SubAssign,sub_assign where[R:SemiRing]);implMul for Matrixwhere R:SemiRing{type Output=Matrix;fn mul(self,rhs:Self)->Self::Output{(&self).mul(&rhs)}}implMul<&Matrix>for Matrixwhere R:SemiRing{type Output=Matrix;fn mul(self,rhs:&Matrix)->Self::Output{(&self).mul(rhs)}}implMul>for&Matrixwhere R:SemiRing{type Output=Matrix;fn mul(self,rhs:Matrix)->Self::Output{self.mul(&rhs)}}implMul<&Matrix>for&Matrixwhere R:SemiRing{type Output=Matrix;fn mul(self,rhs:&Matrix)->Self::Output{assert_eq!(self.shape.1,rhs.shape.0);if let Some(data)=R::try_matrix_product(&self.data,&rhs.data){return Matrix::from_vec(data);}let rhs=rhs.transpose();Matrix::new_with((self.shape.0,rhs.shape.0),|i,j|{R::dot_product(&self[i],&rhs[j])})}}fn strassen_rec(a:&[R::T],b:&[R::T],c:&mut[R::T],shape:(usize,usize,usize),stride_a:usize,stride_b:usize){let(n,m,p)=shape;fn add_block(a:&[R::T],b:&[R::T],out:&mut[R::T],n:usize,stride_a:usize,stride_b:usize){for((a,b),c)in a.chunks(stride_a).zip(b.chunks(stride_b)).zip(out.chunks_exact_mut(n)){for((a,b),c)in a.iter().zip(b.iter()).zip(c.iter_mut()){*c=R::add(a,b);}}}fn sub_block(a:&[R::T],b:&[R::T],out:&mut[R::T],n:usize,stride_a:usize,stride_b:usize){for((a,b),c)in a.chunks(stride_a).zip(b.chunks(stride_b)).zip(out.chunks_exact_mut(n)){for((a,b),c)in a.iter().zip(b.iter()).zip(c.iter_mut()){*c=R::sub(a,b);}}}if n.min(m).min(p)<=128{let transposed:Vec<_>=(0..p).flat_map(|j|(0..m).map(move|i|b[i*stride_b+j].clone())).collect();for(a,c)in a.chunks(stride_a).zip(c.chunks_exact_mut(p)){for(b,c)in transposed.chunks_exact(m).zip(c){*c=R::dot_product(&a[..m],b);}}return;}let(h,k,w)=(n/2,m/2,p/2);let a11=0;let a12=k;let a21=h*stride_a;let a22=a21+k;let b11=0;let b12=w;let b21=k*stride_b;let b22=b21+w;let block=h*w;let mut buf=vec![R::zero();h*k+k*w+block*7];let(s1,rest)=buf.split_at_mut(h*k);let(s2,m_buf)=rest.split_at_mut(k*w);let(m1,rest)=m_buf.split_at_mut(block);let(m2,rest)=rest.split_at_mut(block);let(m3,rest)=rest.split_at_mut(block);let(m4,rest)=rest.split_at_mut(block);let(m5,rest)=rest.split_at_mut(block);let(m6,m7)=rest.split_at_mut(block);add_block::(&a[a11..],&a[a22..],s1,k,stride_a,stride_a);add_block::(&b[b11..],&b[b22..],s2,w,stride_b,stride_b);strassen_rec::(s1,s2,m1,(h,k,w),k,w);add_block::(&a[a21..],&a[a22..],s1,k,stride_a,stride_a);strassen_rec::(s1,&b[b11..],m2,(h,k,w),k,stride_b);sub_block::(&b[b12..],&b[b22..],s2,w,stride_b,stride_b);strassen_rec::(&a[a11..],s2,m3,(h,k,w),stride_a,w);sub_block::(&b[b21..],&b[b11..],s2,w,stride_b,stride_b);strassen_rec::(&a[a22..],s2,m4,(h,k,w),stride_a,w);add_block::(&a[a11..],&a[a12..],s1,k,stride_a,stride_a);strassen_rec::(s1,&b[b22..],m5,(h,k,w),k,stride_b);sub_block::(&a[a21..],&a[a11..],s1,k,stride_a,stride_a);add_block::(&b[b11..],&b[b12..],s2,w,stride_b,stride_b);strassen_rec::(s1,s2,m6,(h,k,w),k,w);sub_block::(&a[a12..],&a[a22..],s1,k,stride_a,stride_a);add_block::(&b[b21..],&b[b22..],s2,w,stride_b,stride_b);strassen_rec::(s1,s2,m7,(h,k,w),k,w);let c11=0;let c12=w;let c21=h*p;let c22=c21+w;for((((m1,m4),m5),m7),c)in m1.iter().zip(m4.iter()).zip(m5.iter()).zip(m7.iter()).zip(c[c11..].chunks_mut(p).flat_map(|c|c.iter_mut().take(w))){*c=R::add(m1,m4);R::sub_assign(c,m5);R::add_assign(c,m7);}for((m3,m5),c)in m3.iter().zip(m5.iter()).zip(c[c12..].chunks_mut(p).flat_map(|c|c.iter_mut().take(w))){*c=R::add(m3,m5);}for((m2,m4),c)in m2.iter().zip(m4.iter()).zip(c[c21..].chunks_mut(p).flat_map(|c|c.iter_mut().take(w))){*c=R::add(m2,m4);}for((((m1,m2),m3),m6),c)in m1.iter().zip(m2.iter()).zip(m3.iter()).zip(m6.iter()).zip(c[c22..].chunks_mut(p).flat_map(|c|c.iter_mut().take(w))){*c=R::sub(m1,m2);R::add_assign(c,m3);R::add_assign(c,m6);}}implMatrixwhere R:Ring{pub fn mul_strassen(&self,rhs:&Matrix)->Matrix{assert_eq!(self.shape.1,rhs.shape.0);if let Some(data)=R::try_matrix_product(&self.data,&rhs.data){return Matrix::from_vec(data);}let(n,m)=self.shape;let p=rhs.shape.1;if n==0||m==0||p==0{return Matrix::zeros((n,p));}let split=n.min(m).min(p).div_ceil(128).next_power_of_two();if split<=2{return self*rhs;}let rows=n.div_ceil(split)*split;let inner=m.div_ceil(split)*split;let cols=p.div_ceil(split)*split;let mut a=vec![R::zero();rows*inner];for(a,data)in a.chunks_exact_mut(inner).zip(&self.data){a[..m].clone_from_slice(data);}let mut b=vec![R::zero();inner*cols];for(b,data)in b.chunks_exact_mut(cols).zip(&rhs.data){b[..p].clone_from_slice(data);}let mut c=vec![R::zero();rows*cols];strassen_rec::(&a,&b,&mut c,(rows,inner,cols),inner,cols);let mut res=Matrix::zeros((n,p));for(data,c)in res.data.iter_mut().zip(c.chunks_exact(cols)){data.clone_from_slice(&c[..p]);}res}}implMulAssign<&R::T>for Matrixwhere R:SemiRing{fn mul_assign(&mut self,rhs:&R::T){for i in 0..self.shape.0{for j in 0..self.shape.1{R::mul_assign(&mut self[(i,j)],rhs);}}}}implNeg for Matrixwhere R:SemiRing{type Output=Self;fn neg(self)->Self::Output{self.map(|x|R::neg(x))}}implNeg for&Matrixwhere R:SemiRing{type Output=Matrix;fn neg(self)->Self::Output{self.map(|x|R::neg(x))}}implMatrixwhere R:SemiRing{pub fn pow(self,mut n:usize)->Self{assert_eq!(self.shape.0,self.shape.1);let mut res=Matrix::eye(self.shape);let mut x=self;while n>0{if n&1==1{res=&res*&x;}n>>=1;if n!=0{x=&x*&x;}}res}}implMatrixwhere R:Ring{pub fn pow_strassen(self,mut n:usize)->Self{assert_eq!(self.shape.0,self.shape.1);let mut res=Matrix::eye(self.shape);let mut x=self;while n>0{if n&1==1{res=res.mul_strassen(&x);}n>>=1;if n!=0{x=x.mul_strassen(&x);}}res}}} // codesnip-guard: MultiplicativeOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::multiplicative_operation_impl::MultiplicativeOperation;#[cfg_attr(any(),rustfmt::skip)]mod multiplicative_operation_impl{use super::*;use std::{marker::PhantomData,ops::{Div,Mul}};#[doc=" $\\times$"]pub struct MultiplicativeOperationwhere T:Clone+One+Mul{_marker:PhantomDataT>}implMagma for MultiplicativeOperationwhere T:Clone+One+Mul{type T=T;#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{x.clone()*y.clone()}}implUnital for MultiplicativeOperationwhere T:Clone+One+Mul{#[inline]fn unit()->Self::T{One::one()}}implAssociative for MultiplicativeOperationwhere T:Clone+One+Mul{}implCommutative for MultiplicativeOperationwhere T:Clone+One+Mul{}implInvertible for MultiplicativeOperationwhere T:Clone+One+Mul+Div{#[inline]fn inverse(x:&Self::T)->Self::T{Self::unit().div(x.clone())}#[inline]fn rinv_operate(x:&Self::T,y:&Self::T)->Self::T{(x.clone()).div(y.clone())}}} // 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: 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: container #[cfg_attr(any(),rustfmt::skip)]pub use self::container::{Container,ContainerEntry};#[cfg_attr(any(),rustfmt::skip)]mod container{use std::{cmp::Ord,collections::{BTreeMap,HashMap,btree_map,hash_map},hash::{BuildHasher,Hash},iter::FusedIterator};pub trait Container{type Key;type Value;type Entry<'a>:ContainerEntry<'a,Key=Self::Key,Value=Self::Value>where Self:'a,Self::Key:'a,Self::Value:'a;type Iter<'a>:Iteratorwhere Self:'a,Self::Key:'a,Self::Value:'a;type Drain<'a>:Iteratorwhere Self:'a,Self::Key:'a,Self::Value:'a;fn get(&self,key:&Self::Key)->Option<&Self::Value>;fn get_mut(&mut self,key:&Self::Key)->Option<&mut Self::Value>;fn insert(&mut self,key:Self::Key,value:Self::Value)->Option;fn remove(&mut self,key:&Self::Key)->Option;fn entry(&mut self,key:Self::Key)->Self::Entry<'_>;fn iter(&self)->Self::Iter<'_>;fn drain(&mut self)->Self::Drain<'_>;}pub trait ContainerEntry<'a>{type Key:'a;type Value:'a;fn or_default(self)->&'a mut Self::Value where Self::Value:Default;fn or_insert(self,default:Self::Value)->&'a mut Self::Value;fn or_insert_with(self,default:F)->&'a mut Self::Value where F:FnOnce()->Self::Value;fn or_insert_with_key(self,default:F)->&'a mut Self::Value where F:FnOnce(&Self::Key)->Self::Value;fn key(&self)->&Self::Key;fn and_modify(self,f:F)->Self where F:FnOnce(&mut Self::Value);}#[derive(Debug)]pub struct BTreeMapDrain<'a,K,V>{inner:&'a mut BTreeMap}implContainer for BTreeMapwhere K:Ord{type Key=K;type Value=V;type Entry<'a>=btree_map::Entry<'a,K,V>where K:'a,V:'a;type Iter<'a>=btree_map::Iter<'a,K,V>where K:'a,V:'a;type Drain<'a>=BTreeMapDrain<'a,K,V>where K:'a,V:'a;fn get(&self,key:&Self::Key)->Option<&Self::Value>{self.get(key)}fn get_mut(&mut self,key:&Self::Key)->Option<&mut Self::Value>{self.get_mut(key)}fn insert(&mut self,key:Self::Key,value:Self::Value)->Option{self.insert(key,value)}fn remove(&mut self,key:&Self::Key)->Option{self.remove(key)}fn entry(&mut self,key:Self::Key)->Self::Entry<'_>{self.entry(key)}fn iter(&self)->Self::Iter<'_>{self.iter()}fn drain(&mut self)->Self::Drain<'_>{BTreeMapDrain{inner:self}}}implIterator for BTreeMapDrain<'_,K,V>where K:Ord{type Item=(K,V);fn next(&mut self)->Option{self.inner.pop_first()}}implDoubleEndedIterator for BTreeMapDrain<'_,K,V>where K:Ord{fn next_back(&mut self)->Option{self.inner.pop_last()}}implExactSizeIterator for BTreeMapDrain<'_,K,V>where K:Ord{fn len(&self)->usize{self.inner.len()}}implFusedIterator for BTreeMapDrain<'_,K,V>where K:Ord{}impl<'a,K,V>ContainerEntry<'a>for btree_map::Entry<'a,K,V>where K:'a+Ord,V:'a{type Key=K;type Value=V;fn or_default(self)->&'a mut Self::Value where Self::Value:Default{self.or_default()}fn or_insert(self,default:Self::Value)->&'a mut Self::Value{self.or_insert(default)}fn or_insert_with(self,default:F)->&'a mut Self::Value where F:FnOnce()->Self::Value{self.or_insert_with(default)}fn or_insert_with_key(self,default:F)->&'a mut Self::Value where F:FnOnce(&Self::Key)->Self::Value{self.or_insert_with_key(default)}fn key(&self)->&Self::Key{self.key()}fn and_modify(self,f:F)->Self where F:FnOnce(&mut Self::Value){self.and_modify(f)}}implContainer for HashMapwhere K:Eq+Hash,S:BuildHasher{type Key=K;type Value=V;type Entry<'a>=hash_map::Entry<'a,K,V>where S:'a,K:'a,V:'a;type Iter<'a>=hash_map::Iter<'a,K,V>where S:'a,K:'a,V:'a;type Drain<'a>=hash_map::Drain<'a,K,V>where S:'a,K:'a,V:'a;fn get(&self,key:&Self::Key)->Option<&Self::Value>{self.get(key)}fn get_mut(&mut self,key:&Self::Key)->Option<&mut Self::Value>{self.get_mut(key)}fn insert(&mut self,key:Self::Key,value:Self::Value)->Option{self.insert(key,value)}fn remove(&mut self,key:&Self::Key)->Option{self.remove(key)}fn entry(&mut self,key:Self::Key)->Self::Entry<'_>{self.entry(key)}fn iter(&self)->Self::Iter<'_>{self.iter()}fn drain(&mut self)->Self::Drain<'_>{self.drain()}}impl<'a,K,V>ContainerEntry<'a>for hash_map::Entry<'a,K,V>where K:'a+Eq+Hash,V:'a{type Key=K;type Value=V;fn or_default(self)->&'a mut Self::Value where Self::Value:Default{self.or_default()}fn or_insert(self,default:Self::Value)->&'a mut Self::Value{self.or_insert(default)}fn or_insert_with(self,default:F)->&'a mut Self::Value where F:FnOnce()->Self::Value{self.or_insert_with(default)}fn or_insert_with_key(self,default:F)->&'a mut Self::Value where F:FnOnce(&Self::Key)->Self::Value{self.or_insert_with_key(default)}fn key(&self)->&Self::Key{self.key()}fn and_modify(self,f:F)->Self where F:FnOnce(&mut Self::Value){self.and_modify(f)}}} // codesnip-guard: integer #[cfg_attr(any(),rustfmt::skip)]pub use self::integer::{BinaryRepr,ExtendedGcd,IntBase,Saturating,Saturatingable,Signed,Unsigned,Wrapping,Wrappingable};#[cfg_attr(any(),rustfmt::skip)]mod integer{use super::{Bounded,One,Scan,ScanSource,Zero};use std::{convert::TryFrom,fmt::{self,Display},iter::{Product,Sum},ops::{Add,AddAssign,BitAnd,BitAndAssign,BitOr,BitOrAssign,BitXor,BitXorAssign,Div,DivAssign,Mul,MulAssign,Neg,Not,Rem,RemAssign,Shl,ShlAssign,Shr,ShrAssign,Sub,SubAssign},str::FromStr};#[doc=" Trait for basic primitive integer operations."]pub trait IntBase:Copy+Bounded+Zero+One+Eq+Ord+Default+FromStr+Display+Add+Sub+Mul+Div+Rem+AddAssign+SubAssign+MulAssign+DivAssign+RemAssign+Sum+Product{type Error;fn div_euclid(self,rhs:Self)->Self;fn rem_euclid(self,rhs:Self)->Self;fn pow(self,exp:u32)->Self;fn from_str_radix(src:&str,radix:u32)->Result;fn ilog(self,base:Self)->u32;fn ilog2(self)->u32;fn ilog10(self)->u32;fn isqrt(self)->Self;fn midpoint(self,rhs:Self)->Self;}macro_rules!impl_int_base{($($t:ty)*)=>{$(impl IntBase for$t{type Error=std::num::ParseIntError;fn div_euclid(self,rhs:Self)->Self{self.div_euclid(rhs)}fn rem_euclid(self,rhs:Self)->Self{self.rem_euclid(rhs)}fn pow(self,exp:u32)->Self{self.pow(exp)}fn from_str_radix(src:&str,radix:u32)->Result{Self::from_str_radix(src,radix)}fn ilog(self,base:Self)->u32{self.ilog(base)}fn ilog2(self)->u32{self.ilog2()}fn ilog10(self)->u32{self.ilog10()}fn isqrt(self)->Self{self.isqrt()}fn midpoint(self,rhs:Self)->Self{self.midpoint(rhs)}})*};}impl_int_base!(u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize);#[doc=" extended_gcd(a,b): ax + by = g = gcd(a,b)"]pub struct ExtendedGcd{#[doc=" gcd"]pub g:T::Unsigned,pub x:T,pub y:T}#[doc=" Trait for unsigned integer operations."]pub trait Unsigned:IntBase{type Signed:Signed;fn signed(self)->Self::Signed;fn abs_diff(self,other:Self)->Self;fn div_ceil(self,rhs:Self)->Self;fn is_power_of_two(self)->bool;fn next_power_of_two(self)->Self;fn is_multiple_of(self,rhs:Self)->bool;fn next_multiple_of(self,rhs:Self)->Self;fn gcd(self,other:Self)->Self;fn lcm(self,other:Self)->Self{if self.is_zero()&&other.is_zero(){Self::zero()}else{self/self.gcd(other)*other}}fn mod_inv(self,modulo:Self)->Self{debug_assert!(!modulo.is_zero(),"modulo must be non-zero");if modulo.is_one(){return Self::zero();}let(mut a,mut b)=(self,modulo);let(mut u,mut v)=(Self::one(),Self::zero());let mut negative=true;while!a.is_zero(){let k=b/a;v+=k*u;b-=k*a;std::mem::swap(&mut u,&mut v);std::mem::swap(&mut b,&mut a);negative=!negative;}debug_assert!(b.is_one(),"not coprime");if negative{v.mod_neg(modulo)}else{v}}fn mod_add(self,rhs:Self,modulo:Self)->Self;fn mod_sub(self,rhs:Self,modulo:Self)->Self;fn mod_mul(self,rhs:Self,modulo:Self)->Self;fn mod_neg(self,modulo:Self)->Self{debug_assert!(!modulo.is_zero(),"modulo must be non-zero");debug_assert!(self{type Unsigned:Unsigned;fn unsigned(self)->Self::Unsigned;fn abs(self)->Self;fn abs_diff(self,other:Self)->Self::Unsigned;fn is_negative(self)->bool;fn is_positive(self)->bool;fn signum(self)->Self;fn extgcd(self,other:Self)->ExtendedGcd{let(mut a,mut b)=(self,other);let(mut u,mut v,mut x,mut y)=(Self::one(),Self::zero(),Self::zero(),Self::one());while!a.is_zero(){let k=b/a;x-=k*u;y-=k*v;b-=k*a;std::mem::swap(&mut x,&mut u);std::mem::swap(&mut y,&mut v);std::mem::swap(&mut b,&mut a);}if b.is_negative(){b=-b;x=-x;y=-y;}ExtendedGcd{g:b.unsigned(),x,y}}}macro_rules!impl_unsigned_signed{($([$($tt:tt)*])*)=>{$(impl_unsigned_signed!($($tt)*);)*};($unsigned:ident$signed:ident$upperty:ident)=>{impl_unsigned_signed!(@inner$unsigned$signed fn mod_mul(self,rhs:Self,modulo:Self)->Self{debug_assert!(!modulo.is_zero(),"modulo must be non-zero");(self as$upperty*rhs as$upperty%modulo as$upperty)as$unsigned});};(u128 i128)=>{impl_unsigned_signed!(@inner u128 i128 fn mod_mul(self,rhs:Self,modulo:Self)->Self{debug_assert!(!modulo.is_zero(),"modulo must be non-zero");const MASK64:u128=0xffff_ffff_ffff_ffff;let(au,ad)=(self>>64,self&MASK64);let(bu,bd)=(rhs>>64,rhs&MASK64);let p0=ad*bd%modulo;let p2=au*bu%modulo;let mut x=[p0 as u64,(p0>>64)as u64,p2 as u64,(p2>>64)as u64,];let p1=(au*bd%modulo).mod_add(ad*bu%modulo,modulo);let(p1_lo,p1_hi)=((p1&MASK64)as u64,(p1>>64)as u64);let(s1,c1)=x[1].overflowing_add(p1_lo);x[1]=s1 as u64;let(s2,c2)=x[2].overflowing_add(p1_hi+c1 as u64);x[2]=s2 as u64;let(s3,_)=x[3].overflowing_add(c2 as u64);x[3]=s3 as u64;rem_u256_by_u128(x,modulo)});};(@inner$unsigned:ident$signed:ident$mod_mul:item)=>{impl Unsigned for$unsigned{type Signed=$signed;fn signed(self)->Self::Signed{self as Self::Signed}fn abs_diff(self,other:Self)->Self{self.abs_diff(other)}fn div_ceil(self,rhs:Self)->Self{self.div_ceil(rhs)}fn is_power_of_two(self)->bool{self.is_power_of_two()}fn next_power_of_two(self)->Self{self.next_power_of_two()}fn is_multiple_of(self,rhs:Self)->bool{self.is_multiple_of(rhs)}fn next_multiple_of(self,rhs:Self)->Self{self.next_multiple_of(rhs)}fn gcd(self,other:Self)->Self{let(mut a,mut b)=(self,other);if a.is_zero()||b.is_zero(){return a|b;}let u=a.trailing_zeros();let v=b.trailing_zeros();a>>=u;b>>=v;let k=u.min(v);while a!=b{if a>=a.trailing_zeros();}a<Self{debug_assert!(!modulo.is_zero(),"modulo must be non-zero");debug_assert!(self=modulo){s.wrapping_sub(modulo)}else{s}}fn mod_sub(self,rhs:Self,modulo:Self)->Self{debug_assert!(!modulo.is_zero(),"modulo must be non-zero");debug_assert!(selfSelf::Unsigned{self as Self::Unsigned}fn abs_diff(self,other:Self)->Self::Unsigned{self.abs_diff(other)}fn abs(self)->Self{self.abs()}fn is_negative(self)->bool{self.is_negative()}fn is_positive(self)->bool{self.is_positive()}fn signum(self)->Self{self.signum()}}};}impl_unsigned_signed!([u8 i8 u16][u16 i16 u32][u32 i32 u64][u64 i64 u128][u128 i128][usize isize u128]);fn rem_u256_by_u128(u:[u64;4],v:u128)->u128{#[inline(always)]fn sub_with_borrow_u64(lhs:u64,rhs:u64,borrow:bool)->(u64,bool){let(res,overflow)=lhs.overflowing_sub(rhs);if borrow{let(res,overflow_borrow)=res.overflowing_sub(1);(res,overflow|overflow_borrow)}else{(res,overflow)}}debug_assert!(v!=0);let v_hi=(v>>64)as u64;if v_hi==0{let d=v as u64 as u128;let mut rem:u128=0;for&w in u.iter().rev(){rem=(rem<<64|w as u128)%d;}return rem;}let v_lo=v as u64;let v_shift=v_hi.leading_zeros();let(vn1,vn0)=if v_shift==0{(v_hi,v_lo)}else{let hi=v_hi<>(64-v_shift);let lo=v_lo<>(64-v_shift);un[2]=u[2]<>(64-v_shift);un[3]=u[3]<>(64-v_shift);un[4]=u[3]>>(64-v_shift);}for j in(0..=2).rev(){let num=(un[j+2]as u128)<<64|un[j+1]as u128;let(mut qhat,mut rhat)={let d=vn1 as u128;let q=(num/d).min(u64::MAX as u128);(q as u64,(num-q*d).min(u64::MAX as u128)as u64)};while qhat as u128*vn0 as u128>(rhat as u128)<<64|un[j]as u128{qhat-=1;let t=rhat as u128+vn1 as u128;if t>=1u128<<64{break;}rhat=t as u64;}let p0=qhat as u128*vn0 as u128;let p1=qhat as u128*vn1 as u128;let(p0_hi,p0_lo)=((p0>>64)as u64,p0 as u64);let(p1_hi,p1_lo)=((p1>>64)as u64,p1 as u64);let(r0,borrow)=sub_with_borrow_u64(un[j],p0_lo,false);un[j]=r0;let(r1,borrow1)=sub_with_borrow_u64(un[j+1],p0_hi,borrow);let(r1,borrow2)=sub_with_borrow_u64(r1,p1_lo,false);let borrow=borrow1||borrow2;un[j+1]=r1;let(r2,borrow)=sub_with_borrow_u64(un[j+2],p1_hi,borrow);un[j+2]=r2;assert!(!borrow);}((un[1]as u128)<<64|un[0]as u128)>>v_hi.leading_zeros()}#[doc=" Trait for operations of integer in binary representation."]pub trait BinaryRepr:Sized+Not+BitAnd+BitOr+BitXor+Shl+Shr+BitAndAssign+BitOrAssign+BitXorAssign+ShlAssign+ShrAssign{fn count_ones(self)->Size;fn count_zeros(self)->Size;fn leading_ones(self)->Size;fn leading_zeros(self)->Size;fn reverse_bits(self)->Self;fn rotate_left(self,n:Size)->Self;fn rotate_right(self,n:Size)->Self;fn swap_bytes(self)->Self;fn trailing_ones(self)->Size;fn trailing_zeros(self)->Size;}macro_rules!impl_binary_repr{($($t:ty)*)=>{$(impl BinaryRepr for$t{fn count_ones(self)->u32{self.count_ones()}fn count_zeros(self)->u32{self.count_zeros()}fn leading_ones(self)->u32{self.leading_ones()}fn leading_zeros(self)->u32{self.leading_zeros()}fn reverse_bits(self)->Self{self.reverse_bits()}fn rotate_left(self,n:u32)->Self{self.rotate_left(n)}fn rotate_right(self,n:u32)->Self{self.rotate_right(n)}fn swap_bytes(self)->Self{self.swap_bytes()}fn trailing_ones(self)->u32{self.trailing_ones()}fn trailing_zeros(self)->u32{self.trailing_zeros()}})*};}impl_binary_repr!(u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize);macro_rules!impl_binop{(impl<$T:ident>$Trait:ident$impl:ident for$t:ty)=>{impl<$T>$Trait for$t where$T:$Trait,{type Output=Self;fn$impl(self,rhs:Self)->Self::Output{Self($Trait::$impl(self.0,rhs.0))}}impl<$T>$Trait<$T>for$t where$T:$Trait,{type Output=Self;fn$impl(self,rhs:$T)->Self::Output{Self($Trait::$impl(self.0,rhs))}}};}macro_rules!impl_opassign{(impl<$T:ident>$Trait:ident$impl:ident for$t:ty)=>{impl<$T>$Trait for$t where$T:$Trait,{fn$impl(&mut self,rhs:Self){$Trait::$impl(&mut self.0,rhs.0)}}impl<$T>$Trait<$T>for$t where$T:$Trait,{fn$impl(&mut self,rhs:$T){$Trait::$impl(&mut self.0,rhs)}}};(impl<$T:ident>$Trait:ident$impl:ident for$t:ty=>$F:ident$f:ident)=>{impl<$T>$Trait for$t where$t:$F+Copy,{fn$impl(&mut self,rhs:Self){*self=$F::$f(*self,rhs);}}impl<$T>$Trait<$T>for$t where$t:$F<$T,Output=$t>+Copy,{fn$impl(&mut self,rhs:$T){*self=$F::$f(*self,rhs);}}};}#[derive(Default,PartialEq,Eq,PartialOrd,Ord,Hash,Clone,Copy)]#[repr(transparent)]#[doc=" Wrapper type of arithmetic `saturating_*` operations."]pub struct Saturating(pub T);pub trait Saturatingable:Sized where Saturating:Copy+Bounded+Zero+One+Eq+Ord+Default+FromStr+Display+Add>+Sub>+Mul>+Div>+Rem>+BitAnd>+BitOr>+BitXor>+Shl>+Shr>+AddAssign+SubAssign+MulAssign+DivAssign+RemAssign+BitAndAssign+BitOrAssign+BitXorAssign+ShlAssign+ShrAssign+Not>+Add>+Sub>+Mul>+Div>+Rem>+BitAnd>+BitOr>+BitXor>+AddAssign+SubAssign+MulAssign+DivAssign+RemAssign+BitAndAssign+BitOrAssign+BitXorAssign{fn to_saturating(self)->Saturating{Saturating(self)}fn from_saturating(s:Saturating)->Self{s.0}}implfmt::Debug for Saturatingwhere T:fmt::Debug{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{T::fmt(&self.0,f)}}implBounded for Saturatingwhere T:Bounded{fn maximum()->Self{Self(T::maximum())}fn minimum()->Self{Self(T::minimum())}}implZero for Saturatingwhere T:Zero{fn zero()->Self{Self(T::zero())}}implOne for Saturatingwhere T:One{fn one()->Self{Self(T::one())}}implFromStr for Saturatingwhere T:FromStr{type Err=T::Err;fn from_str(s:&str)->Result{T::from_str(s).map(Self)}}implDisplay for Saturatingwhere T:Display{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{T::fmt(&self.0,f)}}implScan for Saturatingwhere T:Scan{type Output=Self;fn scan(iter:&mut I)->Option{T::scan(iter).map(Self)}}impl_binop!(implDiv div for Saturating);impl_binop!(implRem rem for Saturating);impl_binop!(implBitAnd bitand for Saturating);impl_binop!(implBitOr bitor for Saturating);impl_binop!(implBitXor bitxor for Saturating);impl_opassign!(implAddAssign add_assign for Saturating =>Add add);impl_opassign!(implSubAssign sub_assign for Saturating =>Sub sub);impl_opassign!(implMulAssign mul_assign for Saturating =>Mul mul);impl_opassign!(implDivAssign div_assign for Saturating);impl_opassign!(implRemAssign rem_assign for Saturating);impl_opassign!(implBitAndAssign bitand_assign for Saturating);impl_opassign!(implBitOrAssign bitor_assign for Saturating);impl_opassign!(implBitXorAssign bitxor_assign for Saturating);implNot for Saturatingwhere T:Not{type Output=Self;fn not(self)->Self::Output{Self(Not::not(self.0))}}macro_rules!impl_int_base_for_saturating{($($t:ty)*)=>{$(impl Saturatingable for$t{}impl Add for Saturating<$t>{type Output=Self;fn add(self,rhs:Self)->Self::Output{Self(self.0 .saturating_add(rhs.0))}}impl Add<$t>for Saturating<$t>{type Output=Self;fn add(self,rhs:$t)->Self::Output{Self(self.0 .saturating_add(rhs))}}impl Sub for Saturating<$t>{type Output=Self;fn sub(self,rhs:Self)->Self::Output{Self(self.0 .saturating_sub(rhs.0))}}impl Sub<$t>for Saturating<$t>{type Output=Self;fn sub(self,rhs:$t)->Self::Output{Self(self.0 .saturating_sub(rhs))}}impl Mul for Saturating<$t>{type Output=Self;fn mul(self,rhs:Self)->Self::Output{Self(self.0 .saturating_mul(rhs.0))}}impl Mul<$t>for Saturating<$t>{type Output=Self;fn mul(self,rhs:$t)->Self::Output{Self(self.0 .saturating_mul(rhs))}}impl Sum for Saturating<$t>{fn sum>(iter:I)->Self{iter.fold(Self::zero(),|acc,x|acc+x)}}impl Product for Saturating<$t>{fn product>(iter:I)->Self{iter.fold(Self::one(),|acc,x|acc*x)}}impl IntBase for Saturating<$t>{type Error=<$t as IntBase>::Error;fn div_euclid(self,rhs:Self)->Self{Self(self.0 .div_euclid(rhs.0))}fn rem_euclid(self,rhs:Self)->Self{Self(self.0 .rem_euclid(rhs.0))}fn pow(self,exp:u32)->Self{Self(self.0 .saturating_pow(exp))}fn from_str_radix(src:&str,radix:u32)->Result{<$t as IntBase>::from_str_radix(src,radix).map(Self)}fn ilog(self,base:Self)->u32{self.0 .ilog(base.0)}fn ilog2(self)->u32{self.0 .ilog2()}fn ilog10(self)->u32{self.0 .ilog10()}fn isqrt(self)->Self{Self(self.0 .isqrt())}fn midpoint(self,rhs:Self)->Self{Self(self.0 .midpoint(rhs.0))}}impl From<$t>for Saturating<$t>{fn from(t:$t)->Self{Self(t)}})*};}impl_int_base_for_saturating!(u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize);macro_rules!impl_unsigned_signed_for_saturating{($($unsigned:ident$signed:ident)*)=>{$(impl Unsigned for Saturating<$unsigned>{type Signed=Saturating<$signed>;fn signed(self)->Self::Signed{Saturating(TryFrom::try_from(self.0).ok().unwrap_or_else($signed::maximum))}fn abs_diff(self,other:Self)->Self{Self(self.0 .abs_diff(other.0))}fn div_ceil(self,rhs:Self)->Self{Self(self.0 .div_ceil(rhs.0))}fn is_power_of_two(self)->bool{self.0 .is_power_of_two()}fn next_power_of_two(self)->Self{Self(self.0 .next_power_of_two())}fn is_multiple_of(self,rhs:Self)->bool{self.0 .is_multiple_of(rhs.0)}fn next_multiple_of(self,rhs:Self)->Self{Self(self.0 .next_multiple_of(rhs.0))}fn gcd(self,other:Self)->Self{Self(self.0 .gcd(other.0))}fn mod_add(self,rhs:Self,modulo:Self)->Self{Self(self.0 .mod_add(rhs.0,modulo.0))}fn mod_sub(self,rhs:Self,modulo:Self)->Self{Self(self.0 .mod_sub(rhs.0,modulo.0))}fn mod_mul(self,rhs:Self,modulo:Self)->Self{Self(self.0 .mod_mul(rhs.0,modulo.0))}}impl Signed for Saturating<$signed>{type Unsigned=Saturating<$unsigned>;fn unsigned(self)->Self::Unsigned{Saturating(TryFrom::try_from(self.0).ok().unwrap_or_else($unsigned::minimum))}fn abs(self)->Self{Self(self.0 .saturating_abs())}fn abs_diff(self,other:Self)->Self::Unsigned{Saturating(self.0 .abs_diff(other.0))}fn is_negative(self)->bool{self.0 .is_negative()}fn is_positive(self)->bool{self.0 .is_positive()}fn signum(self)->Self{Self(self.0 .signum())}}impl Neg for Saturating<$signed>{type Output=Self;fn neg(self)->Self::Output{Self(self.0 .saturating_neg())}})*};}impl_unsigned_signed_for_saturating!(u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize);macro_rules!impl_binary_repr_for_saturating{($($t:ty)*)=>{$(impl Shlfor Saturating<$t>{type Output=Self;fn shl(self,rhs:u32)->Self::Output{Self(self.0 .checked_shl(rhs).unwrap_or(0))}}impl Shrfor Saturating<$t>{type Output=Self;fn shr(self,rhs:u32)->Self::Output{Self(self.0 .checked_shr(rhs).unwrap_or(0))}}impl ShlAssignfor Saturating<$t>{fn shl_assign(&mut self,rhs:u32){*self=Shl::shl(*self,rhs);}}impl ShrAssignfor Saturating<$t>{fn shr_assign(&mut self,rhs:u32){*self=Shr::shr(*self,rhs);}}impl BinaryRepr for Saturating<$t>{fn count_ones(self)->u32{self.0 .count_ones()}fn count_zeros(self)->u32{self.0 .count_zeros()}fn leading_ones(self)->u32{self.0 .leading_ones()}fn leading_zeros(self)->u32{self.0 .leading_zeros()}fn reverse_bits(self)->Self{Self(self.0 .reverse_bits())}fn rotate_left(self,n:u32)->Self{Self(self.0 .rotate_left(n))}fn rotate_right(self,n:u32)->Self{Self(self.0 .rotate_right(n))}fn swap_bytes(self)->Self{Self(self.0 .swap_bytes())}fn trailing_ones(self)->u32{self.0 .trailing_ones()}fn trailing_zeros(self)->u32{self.0 .trailing_zeros()}})*};}impl_binary_repr_for_saturating!(u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize);#[derive(Default,PartialEq,Eq,PartialOrd,Ord,Hash,Clone,Copy)]#[repr(transparent)]#[doc=" Wrapper type of arithmetic `wrapping_*` operations."]pub struct Wrapping(pub T);pub trait Wrappingable:Sized where Wrapping:Copy+Bounded+Zero+One+Eq+Ord+Default+FromStr+Display+Add>+Sub>+Mul>+Div>+Rem>+BitAnd>+BitOr>+BitXor>+Shl>+Shr>+AddAssign+SubAssign+MulAssign+DivAssign+RemAssign+BitAndAssign+BitOrAssign+BitXorAssign+ShlAssign+ShrAssign+Not>+Add>+Sub>+Mul>+Div>+Rem>+BitAnd>+BitOr>+BitXor>+AddAssign+SubAssign+MulAssign+DivAssign+RemAssign+BitAndAssign+BitOrAssign+BitXorAssign{fn to_wrapping(self)->Wrapping{Wrapping(self)}fn from_wrapping(w:Wrapping)->Self{w.0}}implfmt::Debug for Wrappingwhere T:fmt::Debug{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{T::fmt(&self.0,f)}}implBounded for Wrappingwhere T:Bounded{fn maximum()->Self{Self(T::maximum())}fn minimum()->Self{Self(T::minimum())}}implZero for Wrappingwhere T:Zero{fn zero()->Self{Self(T::zero())}}implOne for Wrappingwhere T:One{fn one()->Self{Self(T::one())}}implFromStr for Wrappingwhere T:FromStr{type Err=T::Err;fn from_str(s:&str)->Result{T::from_str(s).map(Self)}}implDisplay for Wrappingwhere T:Display{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{T::fmt(&self.0,f)}}implScan for Wrappingwhere T:Scan{type Output=Self;fn scan(iter:&mut I)->Option{T::scan(iter).map(Self)}}impl_binop!(implBitAnd bitand for Wrapping);impl_binop!(implBitOr bitor for Wrapping);impl_binop!(implBitXor bitxor for Wrapping);impl_opassign!(implAddAssign add_assign for Wrapping =>Add add);impl_opassign!(implSubAssign sub_assign for Wrapping =>Sub sub);impl_opassign!(implMulAssign mul_assign for Wrapping =>Mul mul);impl_opassign!(implDivAssign div_assign for Wrapping =>Div div);impl_opassign!(implRemAssign rem_assign for Wrapping =>Rem rem);impl_opassign!(implBitAndAssign bitand_assign for Wrapping);impl_opassign!(implBitOrAssign bitor_assign for Wrapping);impl_opassign!(implBitXorAssign bitxor_assign for Wrapping);implNot for Wrappingwhere T:Not{type Output=Self;fn not(self)->Self::Output{Self(Not::not(self.0))}}macro_rules!impl_int_base_for_wrapping{($($t:ty)*)=>{$(impl Wrappingable for$t{}impl Add for Wrapping<$t>{type Output=Self;fn add(self,rhs:Self)->Self::Output{Self(self.0 .wrapping_add(rhs.0))}}impl Add<$t>for Wrapping<$t>{type Output=Self;fn add(self,rhs:$t)->Self::Output{Self(self.0 .wrapping_add(rhs))}}impl Sub for Wrapping<$t>{type Output=Self;fn sub(self,rhs:Self)->Self::Output{Self(self.0 .wrapping_sub(rhs.0))}}impl Sub<$t>for Wrapping<$t>{type Output=Self;fn sub(self,rhs:$t)->Self::Output{Self(self.0 .wrapping_sub(rhs))}}impl Mul for Wrapping<$t>{type Output=Self;fn mul(self,rhs:Self)->Self::Output{Self(self.0 .wrapping_mul(rhs.0))}}impl Mul<$t>for Wrapping<$t>{type Output=Self;fn mul(self,rhs:$t)->Self::Output{Self(self.0 .wrapping_mul(rhs))}}impl Div for Wrapping<$t>{type Output=Self;fn div(self,rhs:Self)->Self::Output{Self(self.0 .wrapping_div(rhs.0))}}impl Div<$t>for Wrapping<$t>{type Output=Self;fn div(self,rhs:$t)->Self::Output{Self(self.0 .wrapping_div(rhs))}}impl Rem for Wrapping<$t>{type Output=Self;fn rem(self,rhs:Self)->Self::Output{Self(self.0 .wrapping_rem(rhs.0))}}impl Rem<$t>for Wrapping<$t>{type Output=Self;fn rem(self,rhs:$t)->Self::Output{Self(self.0 .wrapping_rem(rhs))}}impl Sum for Wrapping<$t>{fn sum>(iter:I)->Self{iter.fold(Self::zero(),|acc,x|acc+x)}}impl Product for Wrapping<$t>{fn product>(iter:I)->Self{iter.fold(Self::one(),|acc,x|acc*x)}}impl IntBase for Wrapping<$t>{type Error=<$t as IntBase>::Error;fn div_euclid(self,rhs:Self)->Self{Self(self.0 .wrapping_div_euclid(rhs.0))}fn rem_euclid(self,rhs:Self)->Self{Self(self.0 .wrapping_rem_euclid(rhs.0))}fn pow(self,exp:u32)->Self{Self(self.0 .wrapping_pow(exp))}fn from_str_radix(src:&str,radix:u32)->Result{<$t as IntBase>::from_str_radix(src,radix).map(Self)}fn ilog(self,base:Self)->u32{self.0 .ilog(base.0)}fn ilog2(self)->u32{self.0 .ilog2()}fn ilog10(self)->u32{self.0 .ilog10()}fn isqrt(self)->Self{Self(self.0 .isqrt())}fn midpoint(self,rhs:Self)->Self{Self(self.0 .midpoint(rhs.0))}}impl From<$t>for Wrapping<$t>{fn from(t:$t)->Self{Self(t)}})*};}impl_int_base_for_wrapping!(u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize);macro_rules!impl_unsigned_signed_for_wrapping{($($unsigned:ident$signed:ident)*)=>{$(impl Unsigned for Wrapping<$unsigned>{type Signed=Wrapping<$signed>;fn signed(self)->Self::Signed{Wrapping(self.0 .signed())}fn abs_diff(self,other:Self)->Self{Self(self.0 .abs_diff(other.0))}fn div_ceil(self,rhs:Self)->Self{Self(self.0 .div_ceil(rhs.0))}fn is_power_of_two(self)->bool{self.0 .is_power_of_two()}fn next_power_of_two(self)->Self{Self(self.0 .next_power_of_two())}fn is_multiple_of(self,rhs:Self)->bool{self.0 .is_multiple_of(rhs.0)}fn next_multiple_of(self,rhs:Self)->Self{Self(self.0 .next_multiple_of(rhs.0))}fn gcd(self,other:Self)->Self{Self(self.0 .gcd(other.0))}fn mod_add(self,rhs:Self,modulo:Self)->Self{Self(self.0 .mod_add(rhs.0,modulo.0))}fn mod_sub(self,rhs:Self,modulo:Self)->Self{Self(self.0 .mod_sub(rhs.0,modulo.0))}fn mod_mul(self,rhs:Self,modulo:Self)->Self{Self(self.0 .mod_mul(rhs.0,modulo.0))}}impl Signed for Wrapping<$signed>{type Unsigned=Wrapping<$unsigned>;fn unsigned(self)->Self::Unsigned{Wrapping(self.0 .unsigned())}fn abs(self)->Self{Self(self.0 .wrapping_abs())}fn abs_diff(self,other:Self)->Self::Unsigned{Wrapping(self.0 .abs_diff(other.0))}fn is_negative(self)->bool{self.0 .is_negative()}fn is_positive(self)->bool{self.0 .is_positive()}fn signum(self)->Self{Self(self.0 .signum())}}impl Neg for Wrapping<$signed>{type Output=Self;fn neg(self)->Self::Output{Self(self.0 .wrapping_neg())}})*};}impl_unsigned_signed_for_wrapping!(u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize);macro_rules!impl_binary_repr_for_wrapping{($($t:ty)*)=>{$(impl Shlfor Wrapping<$t>{type Output=Self;fn shl(self,rhs:u32)->Self::Output{Self(self.0 .wrapping_shl(rhs))}}impl Shrfor Wrapping<$t>{type Output=Self;fn shr(self,rhs:u32)->Self::Output{Self(self.0 .wrapping_shr(rhs))}}impl ShlAssignfor Wrapping<$t>{fn shl_assign(&mut self,rhs:u32){*self=Shl::shl(*self,rhs);}}impl ShrAssignfor Wrapping<$t>{fn shr_assign(&mut self,rhs:u32){*self=Shr::shr(*self,rhs);}}impl BinaryRepr for Wrapping<$t>{fn count_ones(self)->u32{self.0 .count_ones()}fn count_zeros(self)->u32{self.0 .count_zeros()}fn leading_ones(self)->u32{self.0 .leading_ones()}fn leading_zeros(self)->u32{self.0 .leading_zeros()}fn reverse_bits(self)->Self{Self(self.0 .reverse_bits())}fn rotate_left(self,n:u32)->Self{Self(self.0 .rotate_left(n))}fn rotate_right(self,n:u32)->Self{Self(self.0 .rotate_right(n))}fn swap_bytes(self)->Self{Self(self.0 .swap_bytes())}fn trailing_ones(self)->u32{self.0 .trailing_ones()}fn trailing_zeros(self)->u32{self.0 .trailing_zeros()}})*};}impl_binary_repr_for_wrapping!(u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize);} // codesnip-guard: ring #[cfg_attr(any(),rustfmt::skip)]pub use self::ring::*;#[cfg_attr(any(),rustfmt::skip)]mod ring{use super::*;use std::{marker::PhantomData,num::Wrapping,ops::{Add,Mul}};pub trait SemiRing{type T:Clone;type Additive:AbelianMonoid;type Multiplicative:Monoid;#[doc=" additive identity: $0$"]fn zero()->Self::T{::unit()}fn is_zero(x:&Self::T)->bool where Self::T:PartialEq{*x==Self::zero()}#[doc=" multiplicative identity: $1$"]fn one()->Self::T{::unit()}fn is_one(x:&Self::T)->bool where Self::T:PartialEq{*x==Self::one()}#[doc=" additive operaion: $+$"]fn add(x:&Self::T,y:&Self::T)->Self::T{::operate(x,y)}#[doc=" multiplicative operaion: $+$"]fn mul(x:&Self::T,y:&Self::T)->Self::T{::operate(x,y)}fn try_matrix_product(_a:&[Vec],_b:&[Vec])->Option>>{None}fn dot_product(x:&[Self::T],y:&[Self::T])->Self::T{assert_eq!(x.len(),y.len());x.iter().zip(y).fold(Self::zero(),|mut sum,(x,y)|{Self::add_assign(&mut sum,&Self::mul(x,y));sum})}fn add_scaled_assign(x:&mut[Self::T],y:&[Self::T],a:&Self::T){assert_eq!(x.len(),y.len());for(x,y)in x.iter_mut().zip(y){Self::add_assign(x,&Self::mul(a,y));}}fn add_assign(x:&mut Self::T,y:&Self::T){::operate_assign(x,y);}fn mul_assign(x:&mut Self::T,y:&Self::T){::operate_assign(x,y);}}pub trait Ring:SemiRing{#[doc=" additive inverse: $-$"]fn neg(x:&Self::T)->Self::T{::inverse(x)}#[doc=" additive right inversed operaion: $-$"]fn sub(x:&Self::T,y:&Self::T)->Self::T{::rinv_operate(x,y)}fn sub_assign(x:&mut Self::T,y:&Self::T){::rinv_operate_assign(x,y);}}implRing for R where R:SemiRing{}pub trait Field:Ring{#[doc=" multiplicative inverse: $-$"]fn inv(x:&Self::T)->Self::T{::inverse(x)}#[doc=" multiplicative right inversed operaion: $-$"]fn div(x:&Self::T,y:&Self::T)->Self::T{::rinv_operate(x,y)}fn div_assign(x:&mut Self::T,y:&Self::T){::rinv_operate_assign(x,y);}}implField for F where F:Ring{}pub trait DotProduct:Sized+Clone+Zero+Add+Mul{fn try_matrix_product(_a:&[Vec],_b:&[Vec])->Option>>{None}fn add_scaled_assign(x:&mut[Self],y:&[Self],a:&Self){assert_eq!(x.len(),y.len());for(x,y)in x.iter_mut().zip(y){*x=x.clone()+a.clone()*y.clone();}}fn dot_product(x:&[Self],y:&[Self])->Self{assert_eq!(x.len(),y.len());x.iter().zip(y).fold(Self::zero(),|sum,(x,y)|sum+x.clone()*y.clone())}}macro_rules!impl_dot_product{($($t:ty)*)=>{$(impl DotProduct for$t{})*};}impl_dot_product!(u8 u16 u32 u64 usize u128 i8 i16 i32 i64 isize i128 f32 f64);implDotProduct for Wrappingwhere Wrapping:Clone+Zero+Add>+Mul>{}#[doc=" $+,\\times$"]pub struct AddMulOperationwhere T:DotProduct+One{_marker:PhantomDataT>}implSemiRing for AddMulOperationwhere T:DotProduct+One{type T=T;type Additive=AdditiveOperation;type Multiplicative=MultiplicativeOperation;#[inline]fn try_matrix_product(a:&[Vec],b:&[Vec])->Option>>{T::try_matrix_product(a,b)}#[inline]fn dot_product(x:&[Self::T],y:&[Self::T])->Self::T{T::dot_product(x,y)}#[inline]fn add_scaled_assign(x:&mut[Self::T],y:&[Self::T],a:&Self::T){T::add_scaled_assign(x,y,a);}}} // 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: transducer #[cfg_attr(any(),rustfmt::skip)]pub use self::transducer::*;#[cfg_attr(any(),rustfmt::skip)]mod transducer{use super::{AdditiveOperation,Container,ContainerEntry,Monoid,One,Zero};use std::{borrow::Borrow,cell::RefCell,cmp::Ordering,collections::HashMap,fmt::{self,Debug,Formatter},hash::{Hash,RandomState},iter::Peekable,marker::PhantomData,mem::swap,ops::Add};type Marker=PhantomDataT>;pub trait Transducer{type Input;type Output;type State;fn start(&self)->Self::State;fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>;fn accept(&self,state:&Self::State)->bool;#[doc=" Advances after processing the current layer."]fn stepout(&mut self){}fn dp(self,init:M::T)->TransducerDp>where Self:Sized,Self::State:Eq+Hash,M:Monoid{let hash_builder=RandomState::new();self.dp_with(init,| |HashMap::with_hasher(hash_builder.clone()))}fn dp_with(self,init:M::T,create:impl FnMut()->C)->TransducerDpwhere Self:Sized,M:Monoid,C:Container{TransducerDp::new(self,init,create)}fn counting(self)->TransducerDp,Self,HashMap>where Self:Sized,Self::State:Eq+Hash,V:Clone+Zero+One+Add{self.dp(V::one())}fn counting_with(self,create:impl FnMut()->C)->TransducerDp,Self,C>where Self:Sized,V:Clone+Zero+One+Add,C:Container{self.dp_with(V::one(),create)}fn intersection(self,other:U)->IntersectionTransducer<(Self,U)>where Self:Sized,U:Transducer{IntersectionTransducer((self,other))}fn product(self,other:U)->ProductTransducer<(Self,U)>where Self:Sized,U:Transducer{ProductTransducer((self,other))}fn chain(self,other:U)->ChainTransducer<(Self,U)>where Self:Sized,U:Transducer{ChainTransducer((self,other))}#[doc=" Appends a cloned input to each output as `(output, input)`, preserving the state."]fn with_input(self)->WithInputTransducerwhere Self:Sized{WithInputTransducer::new(self)}fn map(self,f:F)->MapTransducerwhere Self:Sized,F:Fn(Self::Output)->U{MapTransducer::new(self,f)}fn try_map(self,f:F)->TryMapTransducerwhere Self:Sized,F:Fn(Self::Output)->Option{TryMapTransducer::new(self,f)}#[doc=" Converts each input without adding a state component."]fn map_input(self,f:F)->MapInputTransducerwhere Self:Sized,F:Fn(&I)->Self::Input{MapInputTransducer::new(self,f)}fn retain(self,pred:F)->RetainTransducerwhere Self:Sized,F:Fn(&Self::Output)->bool{RetainTransducer::new(self,pred)}fn with_fold(self,init:A,f:F)->FoldTransducerwhere Self:Sized,F:Fn(&A,&Self::Output)->A{FoldTransducer::new(self,init,f)}fn with_try_fold(self,init:A,f:F)->TryFoldTransducerwhere Self:Sized,F:Fn(&A,&Self::Output)->Option{TryFoldTransducer::new(self,init,f)}fn accepting(self,pred:F)->AcceptTransducerwhere Self:Sized,F:Fn(&Self::State)->bool{AcceptTransducer::new(self,pred)}}#[doc=" `start`, `relation` and `accept` are independent of the layer and call count."]pub trait StationaryTransducer:Transducer{}implStationaryTransducer for&T where T:StationaryTransducer+?Sized{}implTransducer for&T where T:StationaryTransducer+?Sized{type Input=T::Input;type Output=T::Output;type State=T::State;fn start(&self)->Self::State{T::start(self)}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{T::relation(self,state,input)}fn accept(&self,state:&Self::State)->bool{T::accept(self,state)}}#[doc=" Aggregation follows the container's iteration order."]pub struct TransducerDp{fst:T,pub dp:C,ndp:C,_marker:PhantomDataM>}implClone for TransducerDpwhere T:Clone,C:Clone{fn clone(&self)->Self{Self{fst:self.fst.clone(),dp:self.dp.clone(),ndp:self.ndp.clone(),_marker:PhantomData}}}implDebug for TransducerDpwhere T:Debug,C:Debug{fn fmt(&self,f:&mut Formatter<'_>)->fmt::Result{f.debug_struct("TransducerDp").field("fst",&self.fst).field("dp",&self.dp).field("ndp",&self.ndp).finish()}}implTransducerDpwhere M:Monoid,T:Transducer,C:Container{#[doc=" Calls `create` twice; each call must return an independent empty container."]#[inline]pub fn new(fst:T,init:M::T,mut create:impl FnMut()->C)->Self{let mut dp=create();let ndp=create();dp.insert(fst.start(),init);Self{fst,dp,ndp,_marker:PhantomData}}#[doc=" Calls `sigma` once per reachable state to enumerate its candidate inputs."]pub fn step(&mut self,mut sigma:S)where S:FnMut(&T::State)->I,I:IntoIterator,B:Borrow{self.dp.drain().for_each(|(state,value)|{for input in sigma(&state){if let Some((nstate,_))=self.fst.relation(&state,input.borrow()){self.ndp.entry(nstate).and_modify(|acc|M::operate_assign(acc,&value)).or_insert_with(| |value.clone());}}});swap(&mut self.dp,&mut self.ndp);self.fst.stepout();}#[doc=" `effect(value, output)` must preserve `M::operate` for each output."]pub fn step_effect(&mut self,mut sigma:S,mut effect:F)where S:FnMut(&T::State)->I,I:IntoIterator,B:Borrow,F:FnMut(&M::T,T::Output)->M::T{self.dp.drain().for_each(|(state,value)|{for input in sigma(&state){if let Some((nstate,output))=self.fst.relation(&state,input.borrow()){let nvalue=effect(&value,output);self.ndp.entry(nstate).and_modify(|acc|M::operate_assign(acc,&nvalue)).or_insert(nvalue);}}});swap(&mut self.dp,&mut self.ndp);self.fst.stepout();}pub fn fold_accept(&self)->M::T{let mut acc=M::unit();for(_,value)in self.iter_accept(){M::operate_assign(&mut acc,value);}acc}pub fn iter_accept(&self)->impl Iterator{self.dp.iter().filter(|(state,_)|self.fst.accept(state))}pub fn map_fold_accept(&self,mut f:F,mut map:D)->D where F:FnMut(&T::State)->U,D:Container{for(state,value)in self.iter_accept(){map.entry(f(state)).and_modify(|acc|M::operate_assign(acc,value)).or_insert_with(| |value.clone());}map}#[doc=" Advances `len` further layers and aggregates the accepting states."]#[inline]pub fn run(&mut self,len:usize,mut sigma:S)->M::T where S:FnMut(&T::State)->I,I:IntoIterator,B:Borrow{for _ in 0..len{self.step(&mut sigma);}self.fold_accept()}pub fn run_effect(&mut self,len:usize,mut sigma:S,mut effect:F)->M::T where S:FnMut(&T::State)->I,I:IntoIterator,B:Borrow,F:FnMut(&M::T,T::Output)->M::T{for _ in 0..len{self.step_effect(&mut sigma,&mut effect);}self.fold_accept()}}#[doc=" Runs each component from left to right, stopping at the first rejected transition."]#[derive(Debug,Clone)]pub struct IntersectionTransducer(pub Tuple);macro_rules!impl_intersection_transducer{(@impl$($T:ident)*,$($a:ident)*,$($b:ident)*)=>{implStationaryTransducer for IntersectionTransducer<($($T,)*)>where$($T:StationaryTransducer,)*{}implTransducer for IntersectionTransducer<($($T,)*)>where$($T:Transducer,)*{type Input=A;type Output=($($T::Output,)*);type State=($($T::State,)*);fn start(&self)->Self::State{let Self(($($a,)*))=self;($($a.start(),)*)}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{let Self(($($a,)*))=self;let($($b,)*)=state;$(let($a,$b)=$a.relation($b,input)?;)*Some((($($a,)*),($($b,)*)))}fn accept(&self,state:&Self::State)->bool{let Self(($($a,)*))=self;let($($b,)*)=state;$($a.accept($b))&&*}fn stepout(&mut self){let Self(($($a,)*))=self;$($a.stepout();)*}}};(@inc$($T:ident)*,$($a:ident)*,$($b:ident)*,$TT:ident$aa:ident$bb:ident)=>{impl_intersection_transducer!(@impl$($T)*$TT,$($a)*$aa,$($b)*$bb);};(@inc$($T:ident)*,$($a:ident)*,$($b:ident)*,$TT:ident$aa:ident$bb:ident$($tt:tt)*)=>{impl_intersection_transducer!(@impl$($T)*$TT,$($a)*$aa,$($b)*$bb);impl_intersection_transducer!(@inc$($T)*$TT,$($a)*$aa,$($b)*$bb,$($tt)*);};($($tt:tt)*)=>{impl_intersection_transducer!(@inc,,,$($tt)*);};}impl_intersection_transducer!(T0 a0 b0 T1 a1 b1 T2 a2 b2 T3 a3 b3 T4 a4 b4 T5 a5 b5 T6 a6 b6 T7 a7 b7 T8 a8 b8 T9 a9 b9);#[derive(Debug,Clone)]pub struct ProductTransducer(pub Tuple);macro_rules!impl_product_transducer{(@impl$($T:ident)*,$($a:ident)*,$($b:ident)*,$($c:ident)*)=>{impl<$($T),*>StationaryTransducer for ProductTransducer<($($T,)*)>where$($T:StationaryTransducer,)*{}impl<$($T),*>Transducer for ProductTransducer<($($T,)*)>where$($T:Transducer,)*{type Input=($($T::Input,)*);type Output=($($T::Output,)*);type State=($($T::State,)*);fn start(&self)->Self::State{let Self(($($a,)*))=self;($($a.start(),)*)}fn relation(&self,state:&Self::State,($($c,)*):&Self::Input)->Option<(Self::State,Self::Output)>{let Self(($($a,)*))=self;let($($b,)*)=state;$(let($a,$b)=$a.relation($b,$c)?;)*Some((($($a,)*),($($b,)*)))}fn accept(&self,state:&Self::State)->bool{let Self(($($a,)*))=self;let($($b,)*)=state;$($a.accept($b))&&*}fn stepout(&mut self){let Self(($($a,)*))=self;$($a.stepout();)*}}};(@inc$($T:ident)*,$($a:ident)*,$($b:ident)*,$($c:ident)*,$TT:ident$aa:ident$bb:ident$cc:ident)=>{impl_product_transducer!(@impl$($T)*$TT,$($a)*$aa,$($b)*$bb,$($c)*$cc);};(@inc$($T:ident)*,$($a:ident)*,$($b:ident)*,$($c:ident)*,$TT:ident$aa:ident$bb:ident$cc:ident$($tt:tt)*)=>{impl_product_transducer!(@impl$($T)*$TT,$($a)*$aa,$($b)*$bb,$($c)*$cc);impl_product_transducer!(@inc$($T)*$TT,$($a)*$aa,$($b)*$bb,$($c)*$cc,$($tt)*);};($($tt:tt)*)=>{impl_product_transducer!(@inc,,,,$($tt)*);};}impl_product_transducer!(T0 a0 b0 c0 T1 a1 b1 c1 T2 a2 b2 c2 T3 a3 b3 c3 T4 a4 b4 c4 T5 a5 b5 c5 T6 a6 b6 c6 T7 a7 b7 c7 T8 a8 b8 c8 T9 a9 b9 c9);#[derive(Debug,Clone)]pub struct ChainTransducer(pub Tuple);macro_rules!impl_chain_transducer{(@impl$T_head:ident,$($T_tail:ident)*,$($T_init:ident)*,$T_last:ident,$($T:ident)*,$($a:ident)*,$($b:ident)*,$($c:ident)*)=>{impl<$($T),*>StationaryTransducer for ChainTransducer<($($T,)*)>where$T_head:StationaryTransducer,$($T_tail:StationaryTransducer,)*{}impl<$($T),*>Transducer for ChainTransducer<($($T,)*)>where$T_head:Transducer,$($T_tail:Transducer,)*{type Input=$T_head::Input;type Output=$T_last::Output;type State=($($T::State,)*);fn start(&self)->Self::State{let Self(($($a,)*))=self;($($a.start(),)*)}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{let Self(($($a,)*))=self;let($($b,)*)=state;$(let($c,input)=$a.relation($b,&input)?;)*Some((($($c,)*),input))}fn accept(&self,state:&Self::State)->bool{let Self(($($a,)*))=self;let($($b,)*)=state;$($a.accept($b))&&*}fn stepout(&mut self){let Self(($($a,)*))=self;$($a.stepout();)*}}};(@inc$T0:ident$($T:ident)*,$($a:ident)*,$($b:ident)*,$($c:ident)*,$TT:ident$aa:ident$bb:ident$cc:ident)=>{impl_chain_transducer!(@impl$T0,$($T)*$TT,$T0$($T)*,$TT,$T0$($T)*$TT,$($a)*$aa,$($b)*$bb,$($c)*$cc);};(@inc,$($a:ident)*,$($b:ident)*,$($c:ident)*,$TT:ident$aa:ident$bb:ident$cc:ident$($tt:tt)*)=>{impl_chain_transducer!(@impl$TT,,,$TT,$TT,$($a)*$aa,$($b)*$bb,$($c)*$cc);impl_chain_transducer!(@inc$TT,$($a)*$aa,$($b)*$bb,$($c)*$cc,$($tt)*);};(@inc$T0:ident$($T:ident)*,$($a:ident)*,$($b:ident)*,$($c:ident)*,$TT:ident$aa:ident$bb:ident$cc:ident$($tt:tt)*)=>{impl_chain_transducer!(@impl$T0,$($T)*$TT,$T0$($T)*,$TT,$T0$($T)*$TT,$($a)*$aa,$($b)*$bb,$($c)*$cc);impl_chain_transducer!(@inc$T0$($T)*$TT,$($a)*$aa,$($b)*$bb,$($c)*$cc,$($tt)*);};($($tt:tt)*)=>{impl_chain_transducer!(@inc,,,,$($tt)*);};}impl_chain_transducer!(T0 a0 b0 c0 T1 a1 b1 c1 T2 a2 b2 c2 T3 a3 b3 c3 T4 a4 b4 c4 T5 a5 b5 c5 T6 a6 b6 c6 T7 a7 b7 c7 T8 a8 b8 c8 T9 a9 b9 c9);#[derive(Debug)]pub struct FunctionalTransducer{fn_start:F,fn_relation:G,fn_accept:H,_marker:Marker<(I,O,S)>}implClone for FunctionalTransducerwhere F:Clone,G:Clone,H:Clone{fn clone(&self)->Self{Self{fn_start:self.fn_start.clone(),fn_relation:self.fn_relation.clone(),fn_accept:self.fn_accept.clone(),_marker:PhantomData}}}implFunctionalTransducerwhere F:Fn()->S,G:Fn(&S,&I)->Option<(S,O)>,H:Fn(&S)->bool{pub fn new(fn_start:F,fn_relation:G,fn_accept:H)->Self{Self{fn_start,fn_relation,fn_accept,_marker:PhantomData}}}implStationaryTransducer for FunctionalTransducerwhere F:Fn()->S,G:Fn(&S,&I)->Option<(S,O)>,H:Fn(&S)->bool{}implTransducer for FunctionalTransducerwhere F:Fn()->S,G:Fn(&S,&I)->Option<(S,O)>,H:Fn(&S)->bool{type Input=I;type Output=O;type State=S;fn start(&self)->Self::State{(self.fn_start)()}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{(self.fn_relation)(state,input)}fn accept(&self,state:&Self::State)->bool{(self.fn_accept)(state)}}#[derive(Debug)]pub struct MapTransducer{inner:T,f:F,_marker:Marker}implClone for MapTransducerwhere T:Clone,F:Clone{fn clone(&self)->Self{Self{inner:self.inner.clone(),f:self.f.clone(),_marker:PhantomData}}}implMapTransducer{pub fn new(inner:T,f:F)->Self where T:Transducer,F:Fn(T::Output)->U{Self{inner,f,_marker:PhantomData}}}implStationaryTransducer for MapTransducerwhere T:StationaryTransducer,F:Fn(T::Output)->U{}implTransducer for MapTransducerwhere T:Transducer,F:Fn(T::Output)->U{type Input=T::Input;type Output=U;type State=T::State;fn start(&self)->Self::State{self.inner.start()}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{let(next_state,output)=self.inner.relation(state,input)?;Some((next_state,(self.f)(output)))}fn accept(&self,state:&Self::State)->bool{self.inner.accept(state)}fn stepout(&mut self){self.inner.stepout();}}#[derive(Debug)]pub struct TryMapTransducer{inner:T,f:F,_marker:Marker}implClone for TryMapTransducerwhere T:Clone,F:Clone{fn clone(&self)->Self{Self{inner:self.inner.clone(),f:self.f.clone(),_marker:PhantomData}}}implTryMapTransducer{pub fn new(inner:T,f:F)->Self where T:Transducer,F:Fn(T::Output)->Option{Self{inner,f,_marker:PhantomData}}}implStationaryTransducer for TryMapTransducerwhere T:StationaryTransducer,F:Fn(T::Output)->Option{}implTransducer for TryMapTransducerwhere T:Transducer,F:Fn(T::Output)->Option{type Input=T::Input;type Output=U;type State=T::State;fn start(&self)->Self::State{self.inner.start()}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{let(next_state,output)=self.inner.relation(state,input)?;(self.f)(output).map(|output|(next_state,output))}fn accept(&self,state:&Self::State)->bool{self.inner.accept(state)}fn stepout(&mut self){self.inner.stepout();}}#[derive(Debug,Clone)]pub struct WithInputTransducer{inner:T}implWithInputTransducer{pub fn new(inner:T)->Self{Self{inner}}}implStationaryTransducer for WithInputTransducerwhere T:StationaryTransducer,T::Input:Clone{}implTransducer for WithInputTransducerwhere T:Transducer,T::Input:Clone{type Input=T::Input;type Output=(T::Output,T::Input);type State=T::State;fn start(&self)->Self::State{self.inner.start()}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{let(next_state,output)=self.inner.relation(state,input)?;Some((next_state,(output,input.clone())))}fn accept(&self,state:&Self::State)->bool{self.inner.accept(state)}fn stepout(&mut self){self.inner.stepout();}}#[derive(Debug)]pub struct MapInputTransducer{inner:T,f:F,_marker:Marker}implClone for MapInputTransducerwhere T:Clone,F:Clone{fn clone(&self)->Self{Self{inner:self.inner.clone(),f:self.f.clone(),_marker:PhantomData}}}implMapInputTransducer{pub fn new(inner:T,f:F)->Self where T:Transducer,F:Fn(&I)->T::Input{Self{inner,f,_marker:PhantomData}}}implStationaryTransducer for MapInputTransducerwhere T:StationaryTransducer,F:Fn(&I)->T::Input{}implTransducer for MapInputTransducerwhere T:Transducer,F:Fn(&I)->T::Input{type Input=I;type Output=T::Output;type State=T::State;fn start(&self)->Self::State{self.inner.start()}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{self.inner.relation(state,&(self.f)(input))}fn accept(&self,state:&Self::State)->bool{self.inner.accept(state)}fn stepout(&mut self){self.inner.stepout();}}#[derive(Debug,Clone)]pub struct RetainTransducer{inner:T,pred:F}implRetainTransducer{pub fn new(inner:T,pred:F)->Self where T:Transducer,F:Fn(&T::Output)->bool{Self{inner,pred}}}implStationaryTransducer for RetainTransducerwhere T:StationaryTransducer,F:Fn(&T::Output)->bool{}implTransducer for RetainTransducerwhere T:Transducer,F:Fn(&T::Output)->bool{type Input=T::Input;type Output=T::Output;type State=T::State;fn start(&self)->Self::State{self.inner.start()}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{let(next_state,output)=self.inner.relation(state,input)?;(self.pred)(&output).then_some((next_state,output))}fn accept(&self,state:&Self::State)->bool{self.inner.accept(state)}fn stepout(&mut self){self.inner.stepout();}}#[derive(Debug,Clone)]pub struct FoldTransducer{inner:T,init:A,f:F}implFoldTransducer{pub fn new(inner:T,init:A,f:F)->Self where T:Transducer,F:Fn(&A,&T::Output)->A{Self{inner,init,f}}}implStationaryTransducer for FoldTransducerwhere T:StationaryTransducer,A:Clone,F:Fn(&A,&T::Output)->A{}implTransducer for FoldTransducerwhere T:Transducer,A:Clone,F:Fn(&A,&T::Output)->A{type Input=T::Input;type Output=T::Output;type State=(T::State,A);fn start(&self)->Self::State{(self.inner.start(),self.init.clone())}fn relation(&self,(state,acc):&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{let(next_state,output)=self.inner.relation(state,input)?;let next_acc=(self.f)(acc,&output);Some(((next_state,next_acc),output))}fn accept(&self,(state,_):&Self::State)->bool{self.inner.accept(state)}fn stepout(&mut self){self.inner.stepout();}}#[derive(Debug,Clone)]pub struct TryFoldTransducer{inner:T,init:A,f:F}implTryFoldTransducer{pub fn new(inner:T,init:A,f:F)->Self where T:Transducer,F:Fn(&A,&T::Output)->Option{Self{inner,init,f}}}implStationaryTransducer for TryFoldTransducerwhere T:StationaryTransducer,A:Clone,F:Fn(&A,&T::Output)->Option{}implTransducer for TryFoldTransducerwhere T:Transducer,A:Clone,F:Fn(&A,&T::Output)->Option{type Input=T::Input;type Output=T::Output;type State=(T::State,A);fn start(&self)->Self::State{(self.inner.start(),self.init.clone())}fn relation(&self,(state,acc):&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{let(next_state,output)=self.inner.relation(state,input)?;let next_acc=(self.f)(acc,&output)?;Some(((next_state,next_acc),output))}fn accept(&self,(state,_):&Self::State)->bool{self.inner.accept(state)}fn stepout(&mut self){self.inner.stepout();}}#[derive(Debug,Clone)]pub struct AcceptTransducer{inner:T,pred:F}implAcceptTransducer{pub fn new(inner:T,pred:F)->Self where T:Transducer,F:Fn(&T::State)->bool{Self{inner,pred}}}implStationaryTransducer for AcceptTransducerwhere T:StationaryTransducer,F:Fn(&T::State)->bool{}implTransducer for AcceptTransducerwhere T:Transducer,F:Fn(&T::State)->bool{type Input=T::Input;type Output=T::Output;type State=T::State;fn start(&self)->Self::State{self.inner.start()}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{self.inner.relation(state,input)}fn accept(&self,state:&Self::State)->bool{self.inner.accept(state)&&(self.pred)(state)}fn stepout(&mut self){self.inner.stepout();}}#[derive(Debug)]pub struct EqualTransducer(PhantomDataT>);implClone for EqualTransducer{fn clone(&self)->Self{Self(PhantomData)}}implEqualTransducer{pub fn new()->Self{Default::default()}}implDefault for EqualTransducer{fn default()->Self{Self(PhantomData)}}implStationaryTransducer for EqualTransducerwhere T:PartialEq{}implTransducer for EqualTransducerwhere T:PartialEq{type Input=(T,T);type Output=();type State=();fn start(&self)->Self::State{}fn relation(&self,_state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{(input.0==input.1).then_some(((),()))}fn accept(&self,_state:&Self::State)->bool{true}}#[derive(Debug)]#[doc=" DFA to accept Less/Greater than (or equal to) in lexicographical order"]pub struct LexicographicalTransducer{ordering:Ordering,equal:bool,_marker:PhantomDataT>}implClone for LexicographicalTransducer{fn clone(&self)->Self{Self{ordering:self.ordering,equal:self.equal,_marker:PhantomData}}}implLexicographicalTransducer{pub fn less_than()->Self{Self{ordering:Ordering::Less,equal:false,_marker:PhantomData}}pub fn less_than_or_equal()->Self{Self{ordering:Ordering::Less,equal:true,_marker:PhantomData}}pub fn greater_than()->Self{Self{ordering:Ordering::Greater,equal:false,_marker:PhantomData}}pub fn greater_than_or_equal()->Self{Self{ordering:Ordering::Greater,equal:true,_marker:PhantomData}}}implStationaryTransducer for LexicographicalTransducerwhere T:Ord{}implTransducer for LexicographicalTransducerwhere T:Ord{type Input=(T,T);type Output=();#[doc=" is equal"]type State=bool;fn start(&self)->Self::State{true}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{if!state{return Some((false,()));}match input.0 .cmp(&input.1){Ordering::Equal=>Some((true,())),ord if ord==self.ordering=>Some((false,())),_=>None,}}fn accept(&self,state:&Self::State)->bool{self.equal||!state}}#[derive(Debug)]#[doc=" DFA to accept Less/Greater than (or equal to) in reversed lexicographical order"]pub struct RevLexicographicalTransducer{ordering:Ordering,equal:bool,_marker:PhantomDataT>}implClone for RevLexicographicalTransducer{fn clone(&self)->Self{Self{ordering:self.ordering,equal:self.equal,_marker:PhantomData}}}implRevLexicographicalTransducer{pub fn less_than()->Self{Self{ordering:Ordering::Less,equal:false,_marker:PhantomData}}pub fn less_than_or_equal()->Self{Self{ordering:Ordering::Less,equal:true,_marker:PhantomData}}pub fn greater_than()->Self{Self{ordering:Ordering::Greater,equal:false,_marker:PhantomData}}pub fn greater_than_or_equal()->Self{Self{ordering:Ordering::Greater,equal:true,_marker:PhantomData}}}implStationaryTransducer for RevLexicographicalTransducerwhere T:Ord{}implTransducer for RevLexicographicalTransducerwhere T:Ord{type Input=(T,T);type Output=();#[doc=" accept"]type State=bool;fn start(&self)->Self::State{self.equal}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{Some((match input.0 .cmp(&input.1){Ordering::Equal=>*state,ord=>ord==self.ordering,},()))}fn accept(&self,state:&Self::State)->bool{*state}}#[derive(Debug)]pub struct SequenceTransducer<'a,T,A>{sequence:&'a[T],_marker:PhantomDataA>}impl<'a,T,A>Clone for SequenceTransducer<'a,T,A>{fn clone(&self)->Self{Self{sequence:self.sequence,_marker:PhantomData}}}impl<'a,T,A>SequenceTransducer<'a,T,A>{pub fn new(sequence:&'a[T])->Self{Self{sequence,_marker:PhantomData}}}implTransducer for SequenceTransducer<'_,T,A>where T:Clone{type Input=A;type Output=T;type State=();fn start(&self)->Self::State{}fn relation(&self,_state:&Self::State,_input:&Self::Input)->Option<(Self::State,Self::Output)>{self.sequence.first().map(|c|((),c.clone()))}fn accept(&self,_state:&Self::State)->bool{true}fn stepout(&mut self){if!self.sequence.is_empty(){self.sequence=&self.sequence[1..];}}}#[derive(Debug)]pub struct RevSequenceTransducer<'a,T,A>{sequence:&'a[T],_marker:PhantomDataA>}impl<'a,T,A>Clone for RevSequenceTransducer<'a,T,A>{fn clone(&self)->Self{Self{sequence:self.sequence,_marker:PhantomData}}}impl<'a,T,A>RevSequenceTransducer<'a,T,A>{pub fn new(sequence:&'a[T])->Self{Self{sequence,_marker:PhantomData}}}implTransducer for RevSequenceTransducer<'_,T,A>where T:Clone{type Input=A;type Output=T;type State=();fn start(&self)->Self::State{}fn relation(&self,_state:&Self::State,_input:&Self::Input)->Option<(Self::State,Self::Output)>{self.sequence.last().map(|c|((),c.clone()))}fn accept(&self,_state:&Self::State)->bool{true}fn stepout(&mut self){if!self.sequence.is_empty(){self.sequence=&self.sequence[..self.sequence.len()-1];}}}pub struct IteratorTransducerwhere I:Iterator{iter:RefCell>,_marker:PhantomDataA>}implClone for IteratorTransducerwhere I:Iterator+Clone{fn clone(&self)->Self{Self{iter:self.iter.clone(),_marker:self._marker}}}implDebug for IteratorTransducerwhere I:Iterator+Debug{fn fmt(&self,f:&mut Formatter<'_>)->fmt::Result{f.debug_struct("IteratorTransducer").field("iter",&self.iter).field("_marker",&self._marker).finish()}}implIteratorTransducerwhere I:Iterator{pub fn new(iter:I)->Self{Self::new_peekable(iter.peekable())}pub fn new_peekable(iter:Peekable)->Self{Self{iter:RefCell::new(iter),_marker:PhantomData}}}implTransducer for IteratorTransducerwhere I:Iterator{type Input=A;type Output=I::Item;type State=();fn start(&self)->Self::State{}fn relation(&self,_state:&Self::State,_input:&Self::Input)->Option<(Self::State,Self::Output)>{self.iter.borrow_mut().peek().cloned().map(|c|((),c))}fn accept(&self,_state:&Self::State)->bool{true}fn stepout(&mut self){self.iter.borrow_mut().next();}}#[derive(Debug)]pub struct MonoidalTransducer(PhantomDataM>);implClone for MonoidalTransducer{fn clone(&self)->Self{Self(PhantomData)}}implMonoidalTransducer{pub fn new()->Self{Default::default()}}implDefault for MonoidalTransducer{fn default()->Self{Self(PhantomData)}}implStationaryTransducer for MonoidalTransducerwhere M:Monoid{}implTransducer for MonoidalTransducerwhere M:Monoid{type Input=M::T;type Output=();type State=M::T;fn start(&self)->Self::State{M::unit()}fn relation(&self,state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{Some((M::operate(state,input),()))}fn accept(&self,_state:&Self::State)->bool{true}}#[derive(Debug)]pub struct IdentityTransducer(PhantomDataI>);implClone for IdentityTransducer{fn clone(&self)->Self{Self(PhantomData)}}implIdentityTransducer{pub fn new()->Self{Default::default()}}implDefault for IdentityTransducer{fn default()->Self{Self(PhantomData)}}implStationaryTransducer for IdentityTransducerwhere I:Clone{}implTransducer for IdentityTransducerwhere I:Clone{type Input=I;type Output=I;type State=();fn start(&self)->Self::State{}fn relation(&self,_state:&Self::State,input:&Self::Input)->Option<(Self::State,Self::Output)>{Some(((),input.clone()))}fn accept(&self,_state:&Self::State)->bool{true}}#[derive(Debug)]pub struct AlwaysAcceptingTransducer(PhantomDataA>);implClone for AlwaysAcceptingTransducer{fn clone(&self)->Self{Self(PhantomData)}}implAlwaysAcceptingTransducer{pub fn new()->Self{Default::default()}}implDefault for AlwaysAcceptingTransducer{fn default()->Self{Self(PhantomData)}}implStationaryTransducer for AlwaysAcceptingTransducer{}implTransducer for AlwaysAcceptingTransducer{type Input=A;type Output=();type State=();fn start(&self)->Self::State{}fn relation(&self,_state:&Self::State,_input:&Self::Input)->Option<(Self::State,Self::Output)>{Some(((),()))}fn accept(&self,_state:&Self::State)->bool{true}}#[doc=" build transducer"]#[doc=""]#[doc=" - `transducer!(A)`"]#[doc=" - `<= seq`, `seq >=`: [`LexicographicalTransducer::less_than_or_equal()`](LexicographicalTransducer::less_than_or_equal) with [`SequenceTransducer`]"]#[doc=" - `>= seq`, `seq <=`: [`LexicographicalTransducer::greater_than_or_equal()`](LexicographicalTransducer::greater_than_or_equal) with [`SequenceTransducer`]"]#[doc=" - `< seq`, `seq >`: [`LexicographicalTransducer::less_than()`](LexicographicalTransducer::less_than) with [`SequenceTransducer`]"]#[doc=" - `> seq`, `seq <`: [`LexicographicalTransducer::greater_than()`](LexicographicalTransducer::greater_than) with [`SequenceTransducer`]"]#[doc=" - `!<= seq`, `seq !>=`: [`RevLexicographicalTransducer::less_than_or_equal()`](RevLexicographicalTransducer::less_than_or_equal) with [`RevSequenceTransducer`]"]#[doc=" - `!>= seq`, `seq !<=`: [`RevLexicographicalTransducer::greater_than_or_equal()`](RevLexicographicalTransducer::greater_than_or_equal) with [`RevSequenceTransducer`]"]#[doc=" - `!< seq`, `seq !>`: [`RevLexicographicalTransducer::less_than()`](RevLexicographicalTransducer::less_than) with [`RevSequenceTransducer`]"]#[doc=" - `!> seq`, `seq !<`: [`RevLexicographicalTransducer::greater_than()`](RevLexicographicalTransducer::greater_than) with [`RevSequenceTransducer`]"]#[doc=" - `<=`: [`LexicographicalTransducer::less_than_or_equal()`](LexicographicalTransducer::less_than_or_equal)"]#[doc=" - `>=`: [`LexicographicalTransducer::greater_than_or_equal()`](LexicographicalTransducer::greater_than_or_equal)"]#[doc=" - `<`: [`LexicographicalTransducer::less_than()`](LexicographicalTransducer::less_than)"]#[doc=" - `>`: [`LexicographicalTransducer::greater_than()`](LexicographicalTransducer::greater_than)"]#[doc=" - `!<=`: [`RevLexicographicalTransducer::less_than_or_equal()`](RevLexicographicalTransducer::less_than_or_equal)"]#[doc=" - `!>=`: [`RevLexicographicalTransducer::greater_than_or_equal()`](RevLexicographicalTransducer::greater_than_or_equal)"]#[doc=" - `!<`: [`RevLexicographicalTransducer::less_than()`](RevLexicographicalTransducer::less_than)"]#[doc=" - `!>`: [`RevLexicographicalTransducer::greater_than()`](RevLexicographicalTransducer::greater_than)"]#[doc=" - `=> f g h`: [`FunctionalTransducer::new(f, g, h)`](FunctionalTransducer)"]#[doc=" - `@id`: [`IdentityTransducer::new()`](IdentityTransducer)"]#[doc=" - `@it e`: [`IteratorTransducer::new(e)`](IteratorTransducer)"]#[doc=" - `@map f`: `@id |>` [`map(f)`](Transducer::map)"]#[doc=" - `@try_map f`: `@id |>` [`try_map(f)`](Transducer::try_map)"]#[doc=" - `@seq e`: [`SequenceTransducer::new(e)`](SequenceTransducer)"]#[doc=" - `@rseq e`: [`RevSequenceTransducer::new(e)`](RevSequenceTransducer)"]#[doc=" - `@`: [`AlwaysAcceptingTransducer::new()`](AlwaysAcceptingTransducer)"]#[doc=" - `A |> method(args...)`: [`Transducer`]`::method(A, args...)`"]#[doc=" - `A |> map(f)`: [`Transducer::map(A, f)`](Transducer::map)"]#[doc=" - `A |> try_map(f)`: [`Transducer::try_map(A, f)`](Transducer::try_map)"]#[doc=" - `A |> retain(f)`: [`Transducer::retain(A, f)`](Transducer::retain)"]#[doc=" - `A |> with_fold(init, f)`: [`Transducer::with_fold(A, init, f)`](Transducer::with_fold)"]#[doc=" - `A |> with_try_fold(init, f)`: [`Transducer::with_try_fold(A, init, f)`](Transducer::with_try_fold)"]#[doc=" - `A |> accepting(f)`: [`Transducer::accepting(A, f)`](Transducer::accepting)"]#[doc=" - `A . B`: [`ChainTransducer((A, B))`](ChainTransducer)"]#[doc=" - `A * B`: [`ProductTransducer((A, B))`](ProductTransducer)"]#[doc=" - `A & B`: [`IntersectionTransducer((A, B))`](IntersectionTransducer)"]#[doc=" - Use a block for Rust expressions containing DSL operators: `{ machine.clone() }`."]#[macro_export]macro_rules!transducer{(@check$e:expr)=>{{#[inline(always)]fn check_transucer(fst:T)->T where T:Transducer{fst}check_transucer($e)}};(@inner($($t:tt)*))=>{$crate::transducer!(@inner$($t)*)};(@inner=>$f:expr,$g:expr,$h:expr$(,)?)=>{$crate::transducer!(@check FunctionalTransducer::new($f,$g,$h))};(@inner=$e:expr)=>{$crate::transducer!(((@id&(@seq&$e)). =))};(@inner<=$e:expr)=>{$crate::transducer!(((@id&(@seq&$e)).<=))};(@inner>=$e:expr)=>{$crate::transducer!(((@id&(@seq&$e)).>=))};(@inner<$e:expr)=>{$crate::transducer!(((@id&(@seq&$e)).<))};(@inner>$e:expr)=>{$crate::transducer!(((@id&(@seq&$e)).>))};(@inner!<=$e:expr)=>{$crate::transducer!(((@id&(@rseq&$e)).!<=))};(@inner!>=$e:expr)=>{$crate::transducer!(((@id&(@rseq&$e)).!>=))};(@inner!<$e:expr)=>{$crate::transducer!(((@id&(@rseq&$e)).!<))};(@inner!>$e:expr)=>{$crate::transducer!(((@id&(@rseq&$e)).!>))};(@inner$e:ident=)=>{$crate::transducer!(@inner=$e)};(@inner$e:ident<=)=>{$crate::transducer!(@inner>=$e)};(@inner$e:ident>=)=>{$crate::transducer!(@inner<=$e)};(@inner$e:ident<)=>{$crate::transducer!(@inner>$e)};(@inner$e:ident>)=>{$crate::transducer!(@inner<$e)};(@inner$e:ident!<=)=>{$crate::transducer!(@inner!>=$e)};(@inner$e:ident!>=)=>{$crate::transducer!(@inner!<=$e)};(@inner$e:ident!<)=>{$crate::transducer!(@inner!>$e)};(@inner$e:ident!>)=>{$crate::transducer!(@inner!<$e)};(@inner=)=>{$crate::transducer!(@check EqualTransducer::new())};(@inner<=)=>{$crate::transducer!(@check LexicographicalTransducer::less_than_or_equal())};(@inner>=)=>{$crate::transducer!(@check LexicographicalTransducer::greater_than_or_equal())};(@inner<)=>{$crate::transducer!(@check LexicographicalTransducer::less_than())};(@inner>)=>{$crate::transducer!(@check LexicographicalTransducer::greater_than())};(@inner!<=)=>{$crate::transducer!(@check RevLexicographicalTransducer::less_than_or_equal())};(@inner!>=)=>{$crate::transducer!(@check RevLexicographicalTransducer::greater_than_or_equal())};(@inner!<)=>{$crate::transducer!(@check RevLexicographicalTransducer::less_than())};(@inner!>)=>{$crate::transducer!(@check RevLexicographicalTransducer::greater_than())};(@inner@id)=>{$crate::transducer!(@check IdentityTransducer::new())};(@inner@it$e:expr)=>{$crate::transducer!(@check IteratorTransducer::new($e))};(@inner@map$f:expr)=>{$crate::transducer!(@check Transducer::map(IdentityTransducer::new(),$f))};(@inner@try_map$f:expr)=>{$crate::transducer!(@check Transducer::try_map(IdentityTransducer::new(),$f))};(@inner@seq$e:expr)=>{$crate::transducer!(@check SequenceTransducer::new($e))};(@inner@rseq$e:expr)=>{$crate::transducer!(@check RevSequenceTransducer::new($e))};(@inner@<$t:ty>)=>{$crate::transducer!(@check AlwaysAcceptingTransducer::<$t>::new())};(@inner@)=>{$crate::transducer!(@check AlwaysAcceptingTransducer::new())};(@inner$e:ident)=>{$crate::transducer!(@check$e)};(@inner$e:block)=>{$crate::transducer!(@check$e)};(@inner$($t:tt)*)=>{$crate::transducer!(@inter[][]$($t)*)};(@inter[$([$($a:tt)*])*])=>{$crate::transducer!(@check IntersectionTransducer(($($crate::transducer!(@inner$($a)*),)*)))};(@inter[][$($b:tt)*])=>{$crate::transducer!(@prod[][]$($b)*)};(@inter[$($a:tt)*][$($b:tt)*])=>{$crate::transducer!(@inter[$($a)*[$($b)*]])};(@inter[$($a:tt)*][$($b:tt)*]&$($t:tt)*)=>{$crate::transducer!(@inter[$($a)*[$($b)*]][]$($t)*)};(@inter[$($a:tt)*][$($b:tt)*]$op:tt$($t:tt)*)=>{$crate::transducer!(@inter[$($a)*][$($b)*$op]$($t)*)};(@prod[$([$($a:tt)*])*])=>{$crate::transducer!(@check ProductTransducer(($($crate::transducer!(@inner$($a)*),)*)))};(@prod[][$($b:tt)*])=>{$crate::transducer!(@chain[][]$($b)*)};(@prod[$($a:tt)*][$($b:tt)*])=>{$crate::transducer!(@prod[$($a)*[$($b)*]])};(@prod[$($a:tt)*][$($b:tt)*]*$($t:tt)*)=>{$crate::transducer!(@prod[$($a)*[$($b)*]][]$($t)*)};(@prod[$($a:tt)*][$($b:tt)*]$op:tt$($t:tt)*)=>{$crate::transducer!(@prod[$($a)*][$($b)*$op]$($t)*)};(@chain[$([$($a:tt)*])*])=>{$crate::transducer!(@check ChainTransducer(($($crate::transducer!(@wrap[]$($a)*),)*)))};(@chain[][$($b:tt)*])=>{$crate::transducer!(@wrap[]$($b)*)};(@chain[$($a:tt)*][$($b:tt)*])=>{$crate::transducer!(@chain[$($a)*[$($b)*]])};(@chain[$($a:tt)*][$($b:tt)*].$($t:tt)*)=>{$crate::transducer!(@chain[$($a)*[$($b)*]][]$($t)*)};(@chain[$($a:tt)*][$($b:tt)*]$op:tt$($t:tt)*)=>{$crate::transducer!(@chain[$($a)*][$($b)*$op]$($t)*)};(@wrap[$($b:tt)*])=>{$crate::transducer!(@inner$($b)*)};(@wrap[$($b:tt)*]|>$($t:tt)*)=>{$crate::transducer!(@wrap_apply[$crate::transducer!(@inner$($b)*)]$($t)*)};(@wrap[$($b:tt)*]$op:tt$($t:tt)*)=>{$crate::transducer!(@wrap[$($b)*$op]$($t)*)};(@wrapped[$e:expr])=>{$crate::transducer!(@check$e)};(@wrapped[$e:expr]|>$($t:tt)*)=>{$crate::transducer!(@wrap_apply[$e]$($t)*)};(@wrap_apply[$e:expr]$method:ident($($args:expr),*$(,)?)$($t:tt)*)=>{$crate::transducer!(@wrapped[Transducer::$method($e$(,$args)*)]$($t)*)};(@id$($t:tt)*)=>{$crate::transducer!(@inner@id$($t)*)};(@it$($t:tt)*)=>{$crate::transducer!(@inner@it$($t)*)};(@map$($t:tt)*)=>{$crate::transducer!(@inner@map$($t)*)};(@try_map$($t:tt)*)=>{$crate::transducer!(@inner@try_map$($t)*)};(@seq$($t:tt)*)=>{$crate::transducer!(@inner@seq$($t)*)};(@rseq$($t:tt)*)=>{$crate::transducer!(@inner@rseq$($t)*)};(@$tag:ident$($t:tt)*)=>{::std::compile_error!(::std::stringify!($tag,$($t)*))};($($t:tt)*)=>{{$crate::transducer!(@inner$($t)*)}};}} // 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())});}