// codesnip-guard: MIntMatrix #[cfg_attr(any(),rustfmt::skip)]pub use self::mint_matrix::MIntMatrix;#[cfg_attr(any(),rustfmt::skip)]mod mint_matrix{use super::{AddMulOperation,DotProduct,MInt,MIntConvert,MIntDotProduct,Matrix,MemorizedFactorial,One,Xorshift,Zero};pub trait MIntMatrixwhere M:MIntDotProduct{#[doc=" det(self + other * x)"]fn determinant_linear(self,other:Self)->Option>>where M:MIntConvert+MIntConvert;fn pow_frobenius(self,k:usize)->Self where M:MIntConvert;}implMIntMatrixfor Matrix>>where M:MIntDotProduct{fn determinant_linear(mut self,other:Self)->Option>>where M:MIntConvert+MIntConvert{let mut rng=Xorshift::new();let a=MInt::from(rng.rand64());let n=self.data.len();for i in 0..n{for j in 0..n{self[i][j]+=other[i][j]*a;}}let mut f=other.determinant_linear_non_singular(self)?;f.reverse();Some(taylor_shift::(f,-a))}fn pow_frobenius(self,k:usize)->Self where M:MIntConvert{assert_eq!(self.shape.0,self.shape.1);let a=self.transpose();let mut rng=Xorshift::new();let f=loop{if let Some(f)=frobenius_decomposition(&a,&mut rng){break f;}};let fk=f.pow(k);let n=f.t.shape.0;if f.blocks.iter().map(|p|(p.0 .len()-1).pow(2)).sum::()*4<=n*n{let mut ft=Matrix::zeros((n,n));let mut first=0;for p in&f.blocks{let d=p.0 .len()-1;for i in first..first+d{for j in first..first+d{MInt::add_scaled_assign(&mut ft[i],&f.t[j],&fk[i][j]);}}first+=d;}&f.t_inv*&ft}else{&(&f.t_inv*&fk)*&f.t}}}implMatrix>>where M:MIntDotProduct{fn determinant_linear_non_singular(mut self,mut other:Self)->Option>>where M:MIntDotProduct{let n=self.data.len();let mut f=MInt::one();for d in 0..n{let i=other.data.iter().position(|other|!other[d].is_zero())?;if i!=d{self.data.swap(i,d);other.data.swap(i,d);f=-f;}f*=other[d][d];let r=other[d][d].inv();for j in 0..n{self[d][j]*=r;other[d][j]*=r;}assert!(other[d][d].is_one());for i in d+1..n{let a=other[i][d];for k in 0..n{self[i][k]=self[i][k]-a*self[d][k];other[i][k]=other[i][k]-a*other[d][k];}}for j in d+1..n{let a=other[d][j];for k in 0..n{self[k][j]=self[k][j]-a*self[k][d];other[k][j]=other[k][j]-a*other[k][d];}}}for s in self.data.iter_mut(){for s in s.iter_mut(){*s=-*s;}}let mut p=self.characteristic_polynomial();for p in p.iter_mut(){*p*=f;}Some(p)}}struct EchelonRowwhere M:MIntDotProduct{pivot:usize,inv:MInt,row:Vec>}struct Polynomial(Vec>)where M:MIntDotProduct;struct FrobeniusDecompositionwhere M:MIntDotProduct{t:Matrix>>,t_inv:Matrix>>,blocks:Vec>}implEchelonRowwhere M:MIntDotProduct{fn reduce(&self,row:&mut[MInt]){let a=-row[self.pivot]*self.inv;if a.is_zero(){return;}let end=self.row.len();MInt::add_scaled_assign(&mut row[self.pivot..end],&self.row[self.pivot..],&a);}}fn generate_frobenius_block(a:&Matrix>>,mut v:Vec>,rows:&mut Vec>,t:&mut Vec>>)->Polynomialwhere M:MIntDotProduct{let n=a.shape.0;loop{let mut row=vec![MInt::zero();n+rows.len()+1];let(x,c)=row.split_at_mut(n);x.copy_from_slice(&v);c[rows.len()]=MInt::one();for r in rows.iter(){r.reduce(&mut row);}if let Some(pivot)=row[..n].iter().position(|x|!x.is_zero()){t.push(v);let u=t.last().unwrap();v=a.data.iter().map(|row|MInt::dot_product(u,row)).collect();rows.push(EchelonRow{pivot,inv:row[pivot].inv(),row});}else{let mut p=row.split_off(n);while p.last().is_some_and(|x|x.is_zero()){p.pop();}return Polynomial(p);}}}implPolynomialwhere M:MIntDotProduct{fn exact_div(mut self,rhs:&Self)->Option{let mut q=vec![MInt::zero();self.0 .len()-rhs.0 .len()+1];let inv=rhs.0 .last().unwrap().inv();for i in(0..q.len()).rev(){q[i]=self.0[i+rhs.0 .len()-1]*inv;MInt::add_scaled_assign(&mut self.0[i..i+rhs.0 .len()],&rhs.0,&-q[i]);}self.0 .iter().all(|x|x.is_zero()).then_some(Self(q))}fn square_mod(&self,p:&Self)->Self{let d=p.0 .len()-1;let mut c=vec![MInt::zero();2*d-1];for(i,&x)in self.0 .iter().enumerate(){MInt::add_scaled_assign(&mut c[i..2*i],&self.0[..i],&(x+x));c[2*i]+=x*x;}for i in(d..c.len()).rev(){let x=c[i];MInt::add_scaled_assign(&mut c[i-d..=i],&p.0,&-x);}c.truncate(d);Self(c)}fn x_pow_mod(&self,k:usize)->Self{let d=self.0 .len()-1;if d==1{return Self(vec![(-self.0[0]).pow(k)]);}let mut r=Self(vec![MInt::zero();d]);r.0[0]=MInt::one();for bit in(0..usize::BITS-k.leading_zeros()).rev(){r=r.square_mod(self);if k>>bit&1!=0{let x=r.0[d-1];for i in(1..d).rev(){r.0[i]=r.0[i-1]-x*self.0[i];}r.0[0]=-x*self.0[0];}}r}}fn frobenius_decomposition(a:&Matrix>>,rng:&mut Xorshift)->Option>where M:MIntDotProduct+MIntConvert{let n=a.shape.0;let mut rows=Vec::with_capacity(n);let mut t=Vec::with_capacity(n);let mut blocks:Vec>=Vec::new();while rows.len()>>=Matrix::from_vec(shifts);if d<32{let(previous,current)=t.split_at_mut(s);for(shift,row)in shifts.data.iter().zip(current){for(factor,source)in shift.iter().zip(previous.iter()){if!factor.is_zero(){MInt::add_scaled_assign(row,source,factor);}}}}else{let previous=Matrix::from_vec(t[..s].to_vec());let correction=&shifts*&previous;for(row,correction)in t[s..].iter_mut().zip(&correction.data){for(x,&y)in row.iter_mut().zip(correction){*x+=y;}}}for row in&mut rows[s..]{let(previous,current)=row.row[n..].split_at_mut(s);for(&x,shift)in current.iter().zip(&shifts.data){MInt::add_scaled_assign(previous,shift,&-x);}}}blocks.push(p);}let mut t_inv=vec![vec![MInt::zero();n];n];for i in(0..n).rev(){let row=&rows[i];let mut c=row.row[n..].to_vec();c.resize(n,MInt::zero());for x in&mut c{*x*=row.inv;}for next in&rows[i+1..]{let factor=-row.row[next.pivot]*row.inv;if!factor.is_zero(){MInt::add_scaled_assign(&mut c,&t_inv[next.pivot],&factor);}}t_inv[row.pivot]=c;}Some(FrobeniusDecomposition{t:Matrix::from_vec(t),t_inv:Matrix::from_vec(t_inv),blocks})}implFrobeniusDecompositionwhere M:MIntDotProduct{fn pow(&self,k:usize)->Matrix>>{let n=self.t.shape.0;let mut a=vec![vec![MInt::zero();n];n];let mut s=0;for p in&self.blocks{let d=p.0 .len()-1;let mut c=p.x_pow_mod(k).0;for row in&mut a[s..s+d]{row[s..s+d].copy_from_slice(&c);let x=c[d-1];for i in(1..d).rev(){c[i]=c[i-1]-x*p.0[i];}c[0]=-x*p.0[0];}s+=d;}Matrix::from_vec(a)}}fn taylor_shift(f:Vec>,a:MInt)->Vec>where M:MIntConvert{let n=f.len();if n==0{return f;}let mf=MemorizedFactorial::new(n);let mut res=vec![MInt::::zero();n];let mut apow=vec![MInt::::one();n];for i in 1..n{apow[i]=apow[i-1]*a;}for j in 0..n{if f[j].is_zero(){continue;}for k in 0..=j{res[k]+=f[j]*apow[j-k]*mf.combination(j,k);}}res}} // codesnip-guard: AdditiveOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::additive_operation_impl::AdditiveOperation;#[cfg_attr(any(),rustfmt::skip)]mod additive_operation_impl{use super::*;use std::{marker::PhantomData,ops::{Add,Neg,Sub}};#[doc=" $+$"]pub struct AdditiveOperationwhere T:Clone+Zero+Add{_marker:PhantomDataT>}implMagma for AdditiveOperationwhere T:Clone+Zero+Add{type T=T;#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{x.clone()+y.clone()}}implUnital for AdditiveOperationwhere T:Clone+Zero+Add{#[inline]fn unit()->Self::T{Zero::zero()}}implAssociative for AdditiveOperationwhere T:Clone+Zero+Add{}implCommutative for AdditiveOperationwhere T:Clone+Zero+Add{}implInvertible for AdditiveOperationwhere T:Clone+Zero+Add+Sub+Neg{#[inline]fn inverse(x:&Self::T)->Self::T{-x.clone()}#[inline]fn rinv_operate(x:&Self::T,y:&Self::T)->Self::T{x.clone()-y.clone()}}} // codesnip-guard: MIntBase #[cfg_attr(any(),rustfmt::skip)]pub use mint_base::{MInt,MIntBase,MIntConvert};#[cfg_attr(any(),rustfmt::skip)]mod mint_base{use super::*;use std::{fmt::{self,Debug,Display},hash::{Hash,Hasher},iter::{Product,Sum},marker::PhantomData,ops::{Add,AddAssign,Div,DivAssign,Mul,MulAssign,Neg,Sub,SubAssign},str::FromStr};#[repr(transparent)]pub struct MIntwhere M:MIntBase{x:M::Inner,_marker:PhantomDataM>}pub trait MIntConvert::Inner>:MIntBase{fn from(x:T)->::Inner;fn into(x:::Inner)->T;fn mod_into()->T;}pub trait MIntBase{type Inner:Sized+Copy+Eq+Debug+Hash;fn get_mod()->Self::Inner;fn mod_zero()->Self::Inner;fn mod_one()->Self::Inner;fn mod_add(x:Self::Inner,y:Self::Inner)->Self::Inner;fn mod_sub(x:Self::Inner,y:Self::Inner)->Self::Inner;fn mod_mul(x:Self::Inner,y:Self::Inner)->Self::Inner;fn mod_div(x:Self::Inner,y:Self::Inner)->Self::Inner;fn mod_neg(x:Self::Inner)->Self::Inner;fn mod_inv(x:Self::Inner)->Self::Inner;fn mod_pow(x:Self::Inner,y:usize)->Self::Inner{let(mut x,mut y,mut z)=(x,y,Self::mod_one());while y>0{if y&1==1{z=Self::mod_mul(z,x);}x=Self::mod_mul(x,x);y>>=1;}z}fn mod_inner(x:Self::Inner)->Self::Inner{x}}implMIntwhere M:MIntConvert{#[inline]pub fn new(x:M::Inner)->Self{Self::new_unchecked(>::from(x))}}implMIntwhere M:MIntBase{#[inline]pub const fn new_unchecked(x:M::Inner)->Self{Self{x,_marker:PhantomData}}#[inline]pub fn get_mod()->M::Inner{M::get_mod()}#[inline]pub fn pow(self,y:usize)->Self{Self::new_unchecked(M::mod_pow(self.x,y))}#[inline]pub fn inv(self)->Self{Self::new_unchecked(M::mod_inv(self.x))}#[inline]pub fn inner(self)->M::Inner{M::mod_inner(self.x)}}implClone for MIntwhere M:MIntBase{#[inline]fn clone(&self)->Self{*self}}implCopy for MIntwhere M:MIntBase{}implDebug for MIntwhere M:MIntBase{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{Debug::fmt(&self.inner(),f)}}implDefault for MIntwhere M:MIntBase{#[inline]fn default()->Self{::zero()}}implPartialEq for MIntwhere M:MIntBase{#[inline]fn eq(&self,other:&Self)->bool{PartialEq::eq(&self.x,&other.x)}}implEq for MIntwhere M:MIntBase{}implHash for MIntwhere M:MIntBase{#[inline]fn hash(&self,state:&mut H){Hash::hash(&self.x,state)}}macro_rules!impl_mint_from{($($t:ty),*)=>{$(implFrom<$t>for MIntwhere M:MIntConvert<$t>,{#[inline]fn from(x:$t)->Self{Self::new_unchecked(>::from(x))}}implFrom>for$t where M:MIntConvert<$t>,{#[inline]fn from(x:MInt)->$t{>::into(x.x)}})*};}impl_mint_from!(u8,u16,u32,u64,u128,usize,i8,i16,i32,i64,i128,isize);implZero for MIntwhere M:MIntBase{#[inline]fn zero()->Self{Self::new_unchecked(M::mod_zero())}}implOne for MIntwhere M:MIntBase{#[inline]fn one()->Self{Self::new_unchecked(M::mod_one())}}implAdd for MIntwhere M:MIntBase{type Output=Self;#[inline]fn add(self,rhs:Self)->Self::Output{Self::new_unchecked(M::mod_add(self.x,rhs.x))}}implSub for MIntwhere M:MIntBase{type Output=Self;#[inline]fn sub(self,rhs:Self)->Self::Output{Self::new_unchecked(M::mod_sub(self.x,rhs.x))}}implMul for MIntwhere M:MIntBase{type Output=Self;#[inline]fn mul(self,rhs:Self)->Self::Output{Self::new_unchecked(M::mod_mul(self.x,rhs.x))}}implDiv for MIntwhere M:MIntBase{type Output=Self;#[inline]fn div(self,rhs:Self)->Self::Output{Self::new_unchecked(M::mod_div(self.x,rhs.x))}}implNeg for MIntwhere M:MIntBase{type Output=Self;#[inline]fn neg(self)->Self::Output{Self::new_unchecked(M::mod_neg(self.x))}}implSum for MIntwhere M:MIntBase{#[inline]fn sum>(iter:I)->Self{iter.fold(::zero(),Add::add)}}implProduct for MIntwhere M:MIntBase{#[inline]fn product>(iter:I)->Self{iter.fold(::one(),Mul::mul)}}impl<'a,M:'a>Sum<&'a MInt>for MIntwhere M:MIntBase{#[inline]fn sum>(iter:I)->Self{iter.fold(::zero(),Add::add)}}impl<'a,M:'a>Product<&'a MInt>for MIntwhere M:MIntBase{#[inline]fn product>(iter:I)->Self{iter.fold(::one(),Mul::mul)}}implDisplay for MIntwhere M:MIntBase{fn fmt(&self,f:&mut fmt::Formatter<'_>)->Result<(),fmt::Error>{write!(f,"{}",self.inner())}}implFromStr for MIntwhere M:MIntConvert+MIntBase{type Err=::Err;#[inline]fn from_str(s:&str)->Result{s.parse::().map(Self::new)}}implScan for MIntwhere M:MIntConvert+MIntBase>{type Output=Self;#[inline]fn scan(source:&mut S)->Option{M::Inner::scan(source).map(Self::new)}fn scan_vec(source:&mut S,size:usize,capacity:usize)->Vec{let mut values:Vec<_>=source.scan_vec::(size,capacity).into_iter().map(Self::new).collect();values.reserve_exact(capacity.saturating_sub(values.len()));values}}macro_rules!impl_mint_ref_binop{($imp:ident,$method:ident,$t:ty)=>{impl$imp<$t>for&$t where M:MIntBase,{type Output=<$t as$imp<$t>>::Output;#[inline]fn$method(self,other:$t)-><$t as$imp<$t>>::Output{$imp::$method(*self,other)}}impl$imp<&$t>for$t where M:MIntBase,{type Output=<$t as$imp<$t>>::Output;#[inline]fn$method(self,other:&$t)-><$t as$imp<$t>>::Output{$imp::$method(self,*other)}}impl$imp<&$t>for&$t where M:MIntBase,{type Output=<$t as$imp<$t>>::Output;#[inline]fn$method(self,other:&$t)-><$t as$imp<$t>>::Output{$imp::$method(*self,*other)}}};}impl_mint_ref_binop!(Add,add,MInt);impl_mint_ref_binop!(Sub,sub,MInt);impl_mint_ref_binop!(Mul,mul,MInt);impl_mint_ref_binop!(Div,div,MInt);macro_rules!impl_mint_ref_unop{($imp:ident,$method:ident,$t:ty)=>{impl$imp for&$t where M:MIntBase,{type Output=<$t as$imp>::Output;#[inline]fn$method(self)-><$t as$imp>::Output{$imp::$method(*self)}}};}impl_mint_ref_unop!(Neg,neg,MInt);macro_rules!impl_mint_ref_op_assign{($imp:ident,$method:ident,$t:ty,$fromimp:ident,$frommethod:ident)=>{impl$imp<$t>for$t where M:MIntBase,{#[inline]fn$method(&mut self,rhs:$t){*self=$fromimp::$frommethod(*self,rhs);}}impl$imp<&$t>for$t where M:MIntBase,{#[inline]fn$method(&mut self,other:&$t){$imp::$method(self,*other);}}};}impl_mint_ref_op_assign!(AddAssign,add_assign,MInt,Add,add);impl_mint_ref_op_assign!(SubAssign,sub_assign,MInt,Sub,sub);impl_mint_ref_op_assign!(MulAssign,mul_assign,MInt,Mul,mul);impl_mint_ref_op_assign!(DivAssign,div_assign,MInt,Div,div);} // codesnip-guard: MIntDotProduct #[cfg_attr(any(),rustfmt::skip)]pub use mint_dot_product::MIntDotProduct;#[cfg_attr(any(),rustfmt::skip)]mod mint_dot_product{use super::{DotProduct,MInt,MIntBase};pub trait MIntDotProduct:MIntBase+Sized{fn try_matrix_product(_a:&[Vec>],_b:&[Vec>])->Option>>>{None}fn dot_product(x:&[MInt],y:&[MInt])->MInt{assert_eq!(x.len(),y.len());x.iter().zip(y).fold(MInt::new_unchecked(Self::mod_zero()),|sum,(&x,&y)|{sum+x*y})}#[doc=" Computes the inner product of `x` and the reversed `y`."]fn dot_product_rev(x:&[MInt],y:&[MInt])->MInt{assert_eq!(x.len(),y.len());const CHUNK_SIZE:usize=if cfg!(all(target_feature="avx2",not(target_feature="avx512f"))){16}else{8};let(x,x_rem)=x.as_chunks::();let(y_rem,y)=y.as_rchunks::();let mut accum=[MInt::new_unchecked(Self::mod_zero());CHUNK_SIZE];for(x,y)in x.iter().zip(y.iter().rev()){for i in 0..CHUNK_SIZE{accum[i]+=x[i]*y[CHUNK_SIZE-1-i];}}let mut sum=accum.into_iter().sum();for(&x,&y)in x_rem.iter().zip(y_rem.iter().rev()){sum+=x*y;}sum}fn add_scaled_assign(x:&mut[MInt],y:&[MInt],a:&MInt){assert_eq!(x.len(),y.len());for(x,y)in x.iter_mut().zip(y){*x+=*a**y;}}}implDotProduct for MIntwhere M:MIntDotProduct{#[inline]fn try_matrix_product(a:&[Vec],b:&[Vec])->Option>>{M::try_matrix_product(a,b)}#[inline]fn dot_product(x:&[Self],y:&[Self])->Self{assert_eq!(x.len(),y.len());M::dot_product(x,y)}#[inline]fn add_scaled_assign(x:&mut[Self],y:&[Self],a:&Self){M::add_scaled_assign(x,y,a);}}} // 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: Xorshift #[cfg_attr(any(),rustfmt::skip)]pub use self::xorshift::Xorshift;#[cfg_attr(any(),rustfmt::skip)]mod xorshift{use std::{collections::hash_map::RandomState,hash::{BuildHasher,Hasher},iter::repeat_with};#[derive(Clone,Debug)]pub struct Xorshift{y:u64}impl Xorshift{pub fn new_with_seed(seed:u64)->Self{Xorshift{y:seed}}pub fn new()->Self{Xorshift::new_with_seed(RandomState::new().build_hasher().finish())}pub fn rand64(&mut self)->u64{self.y^=self.y<<5;self.y^=self.y>>17;self.y^=self.y<<11;self.y}pub fn rand(&mut self,k:u64)->u64{self.rand64()%k}pub fn rands(&mut self,k:u64,n:usize)->Vec{repeat_with(| |self.rand(k)).take(n).collect()}pub fn randf(&mut self)->f64{const UPPER_MASK:u64=0x3FF0_0000_0000_0000;const LOWER_MASK:u64=0x000F_FFFF_FFFF_FFFF;let x=self.rand64();let tmp=UPPER_MASK|(x&LOWER_MASK);let result:f64=f64::from_bits(tmp);f64::from_bits(f64::to_bits(result-1.0)^(x>>63))}pub fn gen_bool(&mut self,p:f64)->bool{self.randf()(&mut self,slice:&mut[T]){let mut n=slice.len();while n>1{let i=self.rand(n as _)as usize;n-=1;slice.swap(i,n);}}}impl Default for Xorshift{fn default()->Self{Xorshift::new_with_seed(0x2b99_2ddf_a232_49d6)}}} // 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: factorial #[cfg_attr(any(),rustfmt::skip)]pub use self::factorial::MemorizedFactorial;#[cfg_attr(any(),rustfmt::skip)]mod factorial{use super::{MInt,MIntConvert,One,Zero};#[derive(Clone,Debug)]pub struct MemorizedFactorialwhere M:MIntConvert{pub fact:Vec>,pub inv_fact:Vec>}implMemorizedFactorialwhere M:MIntConvert{pub fn new(max_n:usize)->Self{let mut fact=vec![MInt::one();max_n+1];let mut inv_fact=vec![MInt::one();max_n+1];for i in 2..=max_n{fact[i]=fact[i-1]*MInt::from(i);}inv_fact[max_n]=fact[max_n].inv();for i in(3..=max_n).rev(){inv_fact[i-1]=inv_fact[i]*MInt::from(i);}Self{fact,inv_fact}}pub fn combination(&self,n:usize,r:usize)->MInt{debug_assert!(nMInt{debug_assert!(nMInt{debug_assert!(n+rMInt{debug_assert!(n0);self.inv_fact[n]*self.fact[n-1]}}} // 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: 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())});}