pub fn solve() { crate::prepare!(); sc!(n, m, _k, (g, _): @DirectedGraphScanner::::new(n, m)); let scc = StronglyConnectedComponent::new(&g); let cg = scc.gen_cgraph(); let mut ans = true; let cs = scc.components(); let mut uf = UnionFind::new(n * 2); for &(u, v) in g.edges.iter() { if scc[u] == scc[v] { uf.unite(u, v + n); uf.unite(u + n, v); } } let bi: Vec<_> = cs .iter() .map(|cs| cs.iter().all(|&c| !uf.same(c, c + n))) .collect(); let ord = cg.topological_sort(); ans &= ord[0] == scc[0]; for w in ord.windows(2) { ans &= cg.adjacencies(w[0]).any(|a| a.to == w[1]); } let mut ok = false; for &u in &ord { if cs[u].len() == 1 { ans &= ok; } else { ans &= !bi[u]; } ok = cs[u].len() >= 2; } pp!(if ans { "Yes" } else { "No" }); } crate::main!(); #[allow(unused_imports)]use std::{cmp::{Ordering,Reverse},collections::{BTreeMap,BTreeSet,BinaryHeap,HashMap,HashSet,VecDeque}}; mod main_macros{#[doc=" Prepare useful macros."]#[doc=" - `prepare!();`: default (all input scanner (`sc!`, `sv!`) + buf print (`pp!`, `dg!`))"]#[doc=" - `prepare!(?);`: interactive (line scanner (`scln!`) + buf print (`pp!`, `dg!`))"]#[macro_export]#[allow(clippy::crate_in_macro_def)]macro_rules!prepare{(@output($dol:tt))=>{#[allow(unused_imports)]use std::io::Write as _;let __out=std::io::stdout();#[allow(unused_mut,unused_variables)]let mut __out=std::io::BufWriter::new(__out.lock());#[allow(unused_macros)]#[doc=" [`iter_print!`] for buffered stdout."]macro_rules!pp{($dol($dol t:tt)*)=>{$dol crate::iter_print!(__out,$dol($dol t)*)}}#[cfg(debug_assertions)]#[allow(unused_macros)]#[doc=" [`iter_print!`] for buffered stderr. Do nothing in release mode."]macro_rules!dg{($dol($dol t:tt)*)=>{{#[allow(unused_imports)]use std::io::Write as _;let __err=std::io::stderr();#[allow(unused_mut,unused_variables)]let mut __err=std::io::BufWriter::new(__err.lock());$dol crate::iter_print!(__err,$dol($dol t)*);let _=__err.flush();}}}#[cfg(not(debug_assertions))]#[allow(unused_macros)]#[doc=" [`iter_print!`] for buffered stderr. Do nothing in release mode."]macro_rules!dg{($dol($dol t:tt)*)=>{}}};(@normal($dol:tt))=>{let __in_buf=read_stdin_all_unchecked();#[allow(unused_mut,unused_variables)]let mut __scanner=Scanner::new(&__in_buf);#[allow(unused_macros)]macro_rules!sc{($dol($dol t:tt)*)=>{$dol crate::scan!(__scanner,$dol($dol t)*)}}#[allow(unused_macros)]macro_rules!sv{($dol($dol t:tt)*)=>{$dol crate::scan_value!(__scanner,$dol($dol t)*)}}};(@interactive($dol:tt))=>{#[allow(unused_macros)]#[doc=" Scan a line, and previous line will be truncated in the next call."]macro_rules!scln{($dol($dol t:tt)*)=>{let __in_buf=read_stdin_line();#[allow(unused_mut,unused_variables)]let mut __scanner=Scanner::new(&__in_buf);$dol crate::scan!(__scanner,$dol($dol t)*)}}#[allow(unused_macros)]#[doc=" Scan a line, and previous line will be truncated in the next call."]macro_rules!svln{($dol($dol t:tt)*)=>{{let __in_buf=read_stdin_line();#[allow(unused_mut,unused_variables)]let mut __scanner=Scanner::new(&__in_buf);$dol crate::scan_value!(__scanner,$dol($dol t)*)}}}};()=>{$crate::prepare!(@output($));$crate::prepare!(@normal($))};(?)=>{$crate::prepare!(@output($));$crate::prepare!(@interactive($))};}#[macro_export]macro_rules!main{()=>{fn main(){solve();}};(avx2)=>{fn main(){#[target_feature(enable="avx2")]unsafe fn solve_avx2(){solve();}unsafe{solve_avx2()}}};(large_stack)=>{fn main(){const STACK_SIZE:usize=512*1024*1024;::std::thread::Builder::new().stack_size(STACK_SIZE).spawn(solve).unwrap().join().unwrap();}};}} pub use self::iter_print::IterPrint; mod iter_print{use std::{fmt::Display,io::{Error,Write}};pub trait IterPrint{fn iter_print(self,writer:&mut W,sep:S,is_head:bool)->Result<(),Error>where W:Write,S:Display;}macro_rules!impl_iter_print_tuple{(@impl,)=>{impl IterPrint for(){fn iter_print(self,_writer:&mut W,_sep:S,_is_head:bool)->Result<(),Error>where W:Write,S:Display{Ok(())}}};(@impl$($A:ident$a:ident)?,$($B:ident$b:ident)*)=>{impl<$($A,)?$($B),*>IterPrint for($($A,)?$($B),*)where$($A:Display,)?$($B:Display),*{fn iter_print(self,writer:&mut W,sep:S,is_head:bool)->Result<(),Error>where W:Write,S:Display{let($($a,)?$($b,)*)=self;$(if is_head{::std::write!(writer,"{}",$a)?;}else{::std::write!(writer,"{}{}",sep,$a)?;})?$(::std::write!(writer,"{}{}",sep,$b)?;)*Ok(())}}};(@inc,,$C:ident$c:ident$($D:ident$d:ident)*)=>{impl_iter_print_tuple!(@impl,);impl_iter_print_tuple!(@inc$C$c,,$($D$d)*);};(@inc$A:ident$a:ident,$($B:ident$b:ident)*,$C:ident$c:ident$($D:ident$d:ident)*)=>{impl_iter_print_tuple!(@impl$A$a,$($B$b)*);impl_iter_print_tuple!(@inc$A$a,$($B$b)*$C$c,$($D$d)*);};(@inc$A:ident$a:ident,$($B:ident$b:ident)*,)=>{impl_iter_print_tuple!(@impl$A$a,$($B$b)*);};($($t:tt)*)=>{impl_iter_print_tuple!(@inc,,$($t)*);};}impl_iter_print_tuple!(A a B b C c D d E e F f G g H h I i J j K k);#[doc=" Print expressions with a separator."]#[doc=" - `iter_print!(writer, args...)`"]#[doc=" - `@sep $expr`: set separator (default: `' '`)"]#[doc=" - `@ns`: alias for `@sep \"\"`"]#[doc=" - `@lf`: alias for `@sep '\\n'`"]#[doc=" - `@sp`: alias for `@sep ' '`"]#[doc=" - `@fmt ($lit, $($expr),*)`: print `format!($lit, $($expr),*)`"]#[doc=" - `@flush`: flush writer (auto insert `!`)"]#[doc=" - `@it $expr`: print iterator"]#[doc=" - `@it1 $expr`: print iterator as 1-indexed"]#[doc=" - `@cw ($char $expr)`: print iterator as `(elem as u8 + $char as u8) as char`"]#[doc=" - `@bw ($byte $expr)`: print iterator as `(elem as u8 + $byte) as char`"]#[doc=" - `@it2d $expr`: print 2d-iterator"]#[doc=" - `@tup $expr`: print tuple (need to import [`IterPrint`])"]#[doc=" - `@ittup $expr`: print iterative tuple (need to import [`IterPrint`])"]#[doc=" - `$expr`: print expr"]#[doc=" - `{ args... }`: scoped"]#[doc=" - `;`: print `'\\n'`"]#[doc=" - `!`: not print `'\\n'` at the end"]#[macro_export]macro_rules!iter_print{(@@fmt$writer:expr,$sep:expr,$is_head:expr,($lit:literal$(,$e:expr)*$(,)?))=>{if!$is_head{::std::write!($writer,"{}",$sep).expect("io error");}::std::write!($writer,$lit,$($e),*).expect("io error");};(@@item$writer:expr,$sep:expr,$is_head:expr,$e:expr)=>{$crate::iter_print!(@@fmt$writer,$sep,$is_head,("{}",$e));};(@@line_feed$writer:expr$(,)?)=>{::std::writeln!($writer).expect("io error");};(@@it$writer:expr,$sep:expr,$is_head:expr,$iter:expr)=>{{let mut iter=$iter.into_iter();if let Some(item)=iter.next(){$crate::iter_print!(@@item$writer,$sep,$is_head,item);}for item in iter{$crate::iter_print!(@@item$writer,$sep,false,item);}}};(@@it1$writer:expr,$sep:expr,$is_head:expr,$iter:expr)=>{{let mut iter=$iter.into_iter();if let Some(item)=iter.next(){$crate::iter_print!(@@item$writer,$sep,$is_head,item+1);}for item in iter{$crate::iter_print!(@@item$writer,$sep,false,item+1);}}};(@@cw$writer:expr,$sep:expr,$is_head:expr,($ch:literal$iter:expr))=>{{let mut iter=$iter.into_iter();let b=$ch as u8;if let Some(item)=iter.next(){$crate::iter_print!(@@item$writer,$sep,$is_head,(item as u8+b)as char);}for item in iter{$crate::iter_print!(@@item$writer,$sep,false,(item as u8+b)as char);}}};(@@bw$writer:expr,$sep:expr,$is_head:expr,($b:literal$iter:expr))=>{{let mut iter=$iter.into_iter();let b:u8=$b;if let Some(item)=iter.next(){$crate::iter_print!(@@item$writer,$sep,$is_head,(item as u8+b)as char);}for item in iter{$crate::iter_print!(@@item$writer,$sep,false,(item as u8+b)as char);}}};(@@it2d$writer:expr,$sep:expr,$is_head:expr,$iter:expr)=>{let mut iter=$iter.into_iter();if let Some(item)=iter.next(){$crate::iter_print!(@@it$writer,$sep,$is_head,item);}for item in iter{$crate::iter_print!(@@line_feed$writer);$crate::iter_print!(@@it$writer,$sep,true,item);}};(@@tup$writer:expr,$sep:expr,$is_head:expr,$tuple:expr)=>{IterPrint::iter_print($tuple,&mut$writer,$sep,$is_head).expect("io error");};(@@ittup$writer:expr,$sep:expr,$is_head:expr,$iter:expr)=>{let mut iter=$iter.into_iter();if let Some(item)=iter.next(){$crate::iter_print!(@@tup$writer,$sep,$is_head,item);}for item in iter{$crate::iter_print!(@@line_feed$writer);$crate::iter_print!(@@tup$writer,$sep,true,item);}};(@@assert_tag item)=>{};(@@assert_tag it)=>{};(@@assert_tag it1)=>{};(@@assert_tag it2d)=>{};(@@assert_tag tup)=>{};(@@assert_tag ittup)=>{};(@@assert_tag$tag:ident)=>{::std::compile_error!(::std::concat!("invalid tag in `iter_print!`: `",std::stringify!($tag),"`"));};(@@inner$writer:expr,$sep:expr,$is_head:expr,@sep$e:expr,$($t:tt)*)=>{$crate::iter_print!(@@inner$writer,$e,$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@ns$($t:tt)*)=>{$crate::iter_print!(@@inner$writer,"",$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@lf$($t:tt)*)=>{$crate::iter_print!(@@inner$writer,'\n',$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@sp$($t:tt)*)=>{$crate::iter_print!(@@inner$writer,' ',$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@flush$($t:tt)*)=>{$writer.flush().expect("io error");$crate::iter_print!(@@inner$writer,$sep,$is_head,!$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@fmt$arg:tt$($t:tt)*)=>{$crate::iter_print!(@@fmt$writer,$sep,$is_head,$arg);$crate::iter_print!(@@inner$writer,$sep,$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@cw$arg:tt$($t:tt)*)=>{$crate::iter_print!(@@cw$writer,$sep,$is_head,$arg);$crate::iter_print!(@@inner$writer,$sep,$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@bw$arg:tt$($t:tt)*)=>{$crate::iter_print!(@@bw$writer,$sep,$is_head,$arg);$crate::iter_print!(@@inner$writer,$sep,$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@$tag:ident$e:expr,$($t:tt)*)=>{$crate::iter_print!(@@assert_tag$tag);$crate::iter_print!(@@$tag$writer,$sep,$is_head,$e);$crate::iter_print!(@@inner$writer,$sep,false,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@$tag:ident$e:expr;$($t:tt)*)=>{$crate::iter_print!(@@assert_tag$tag);$crate::iter_print!(@@$tag$writer,$sep,$is_head,$e);$crate::iter_print!(@@line_feed$writer);$crate::iter_print!(@@inner$writer,$sep,true,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@$tag:ident$e:expr)=>{$crate::iter_print!(@@assert_tag$tag);$crate::iter_print!(@@$tag$writer,$sep,$is_head,$e);$crate::iter_print!(@@inner$writer,$sep,false,);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@$tag:ident$($t:tt)*)=>{::std::compile_error!(::std::concat!("invalid expr in `iter_print!`: `",std::stringify!($($t)*),"`"));};(@@inner$writer:expr,$sep:expr,$is_head:expr,,$($t:tt)*)=>{$crate::iter_print!(@@inner$writer,$sep,$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,;$($t:tt)*)=>{$crate::iter_print!(@@line_feed$writer);$crate::iter_print!(@@inner$writer,$sep,$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,!$(,)?)=>{};(@@inner$writer:expr,$sep:expr,$is_head:expr,!$($t:tt)*)=>{$crate::iter_print!(@@inner$writer,$sep,$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,)=>{$crate::iter_print!(@@line_feed$writer);};(@@inner$writer:expr,$sep:expr,$is_head:expr,{$($t:tt)*}$($rest:tt)*)=>{$crate::iter_print!(@@inner$writer,$sep,$is_head,$($t)*,!);$crate::iter_print!(@@inner$writer,$sep,$is_head,$($rest)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,$($t:tt)*)=>{$crate::iter_print!(@@inner$writer,$sep,$is_head,@item$($t)*);};($writer:expr,$($t:tt)*)=>{{$crate::iter_print!(@@inner$writer,' ',true,$($t)*);}};}} 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]}};}} pub use self::scanner::*; 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 IterScan:Sized{type Output;fn scan<'a,I:Iterator>(iter:&mut I)->Option;}pub trait MarkedIterScan:Sized{type Output;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option;}#[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{let iter=s.split_ascii_whitespace();Self{iter}}}impl<'a,I:Iterator>Scanner<'a,I>{pub fn new_from_iter(iter:I)->Self{Self{iter}}pub fn scan(&mut self)->::Output where T:IterScan{::scan(&mut self.iter).expect("scan error")}pub fn mscan(&mut self,marker:T)->::Output where T:MarkedIterScan{marker.mscan(&mut self.iter).expect("scan error")}pub fn scan_vec(&mut self,size:usize)->Vec<::Output>where T:IterScan{(0..size).map(|_|::scan(&mut self.iter).expect("scan error")).collect()}#[inline]pub fn iter<'b,T>(&'b mut self)->ScannerIter<'a,'b,I,T>where T:IterScan{ScannerIter{inner:self,_marker:std::marker::PhantomData}}}macro_rules!impl_iter_scan{($($t:ty)*)=>{$(impl IterScan for$t{type Output=Self;fn scan<'a,I:Iterator>(iter:&mut I)->Option{iter.next()?.parse::<$t>().ok()}})*};}impl_iter_scan!(char u8 u16 u32 u64 usize i8 i16 i32 i64 isize f32 f64 u128 i128 String);macro_rules!impl_iter_scan_tuple{(@impl$($T:ident)*)=>{impl<$($T:IterScan),*>IterScan for($($T,)*){type Output=($(<$T as IterScan>::Output,)*);fn scan<'a,It:Iterator>(_iter:&mut It)->Option{Some(($(<$T as IterScan>::scan(_iter)?,)*))}}};(@inner$($T:ident)*,)=>{impl_iter_scan_tuple!(@impl$($T)*);};(@inner$($T:ident)*,$U:ident$($Rest:ident)*)=>{impl_iter_scan_tuple!(@impl$($T)*);impl_iter_scan_tuple!(@inner$($T)*$U,$($Rest)*);};($($T:ident)*)=>{impl_iter_scan_tuple!(@inner,$($T)*);};}impl_iter_scan_tuple!(A B C D E F G H I J K);pub struct ScannerIter<'a,'b,I:Iterator,T>{inner:&'b mut Scanner<'a,I>,_marker:std::marker::PhantomDataT>}impl<'a,I,T>Iterator for ScannerIter<'a,'_,I,T>where I:Iterator,T:IterScan{type Item=::Output;#[inline]fn next(&mut self)->Option{::scan(&mut self.inner.iter)}}#[doc=" scan a value with Scanner"]#[doc=""]#[doc=" - `scan_value!(scanner, ELEMENT)`"]#[doc=""]#[doc=" ELEMENT :="]#[doc=" - `$ty`: IterScan"]#[doc=" - `@$expr`: MarkedIterScan"]#[doc=" - `$ty = $expr`: MarkedIterScan"]#[doc=" - `[ELEMENT; $expr]`: vector"]#[doc=" - `[ELEMENT; const $expr]`: array"]#[doc=" - `[ELEMENT]`: iterator"]#[doc=" - `($(ELEMENT)*,)`: tuple"]#[macro_export]macro_rules!scan_value{(@repeat$scanner:expr,[$($t:tt)*]$($len:expr)?)=>{::std::iter::repeat_with(||$crate::scan_value!(@inner$scanner,[]$($t)*))$(.take($len).collect::>())?};(@array$scanner:expr,[$($t:tt)*]$len:expr)=>{$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)+]$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)*]$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)*]$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, IterScan, 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 IterScan>::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)=>{$iter.next()?};(@tag_expr$d:ty,$iter:ident)=>{<$d as IterScan>::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 IterScan for$T{type Output=Self;fn scan<'a,I:Iterator>(iter:&mut I)->Option{let tag=$crate::define_enum_scan!(@tag_expr$d,iter);match tag{$($p=>{$($(let$f=$crate::scan_value!(iter=&mut*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 IterScan for Usize1{type Output=usize;fn scan<'a,I:Iterator>(iter:&mut I)->Option{::scan(iter)?.checked_sub(1)}}#[derive(Debug,Copy,Clone)]pub struct CharWithBase(pub char);impl MarkedIterScan for CharWithBase{type Output=usize;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{Some((::scan(iter)?as u8-self.0 as u8)as usize)}}#[derive(Debug,Copy,Clone)]pub enum Chars{}impl IterScan for Chars{type Output=Vec;fn scan<'a,I:Iterator>(iter:&mut I)->Option{Some(iter.next()?.chars().collect())}}#[derive(Debug,Copy,Clone)]pub struct CharsWithBase(pub char);impl MarkedIterScan for CharsWithBase{type Output=Vec;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{Some(iter.next()?.chars().map(|c|(c as u8-self.0 as u8)as usize).collect())}}#[derive(Debug,Copy,Clone)]pub enum Byte1{}impl IterScan for Byte1{type Output=u8;fn scan<'a,I:Iterator>(iter:&mut I)->Option{let bytes=iter.next()?.as_bytes();assert_eq!(bytes.len(),1);Some(bytes[0])}}#[derive(Debug,Copy,Clone)]pub struct ByteWithBase(pub u8);impl MarkedIterScan for ByteWithBase{type Output=usize;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{Some((::scan(iter)?as u8-self.0)as usize)}}#[derive(Debug,Copy,Clone)]pub enum Bytes{}impl IterScan for Bytes{type Output=Vec;fn scan<'a,I:Iterator>(iter:&mut I)->Option{Some(iter.next()?.bytes().collect())}}#[derive(Debug,Copy,Clone)]pub struct BytesWithBase(pub u8);impl MarkedIterScan for BytesWithBase{type Output=Vec;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{Some(iter.next()?.bytes().map(|c|(c-self.0)as usize).collect())}}#[derive(Debug,Copy,Clone)]pub struct Collect::Output>>where T:IterScan,B:FromIterator<::Output>{size:usize,_marker:PhantomData(T,B)>}implCollectwhere T:IterScan,B:FromIterator<::Output>{pub fn new(size:usize)->Self{Self{size,_marker:PhantomData}}}implMarkedIterScan for Collectwhere T:IterScan,B:FromIterator<::Output>{type Output=B;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{repeat_with(| |::scan(iter)).take(self.size).collect()}}#[derive(Debug,Copy,Clone)]pub struct SizedCollect::Output>>where T:IterScan,B:FromIterator<::Output>{_marker:PhantomData(T,B)>}implIterScan for SizedCollectwhere T:IterScan,B:FromIterator<::Output>{type Output=B;fn scan<'a,I:Iterator>(iter:&mut I)->Option{let size=usize::scan(iter)?;repeat_with(| |::scan(iter)).take(size).collect()}}#[derive(Debug,Copy,Clone)]pub struct Splittedwhere T:IterScan{pat:P,_marker:PhantomDataT>}implSplittedwhere T:IterScan{pub fn new(pat:P)->Self{Self{pat,_marker:PhantomData}}}implMarkedIterScan for Splittedwhere T:IterScan{type Output=Vec<::Output>;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{let mut iter=iter.next()?.split(self.pat);Some(from_fn(| |::scan(&mut iter)).collect())}}implMarkedIterScan for Splittedwhere T:IterScan{type Output=Vec<::Output>;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{let mut iter=iter.next()?.split(self.pat);Some(from_fn(| |::scan(&mut iter)).collect())}}implMarkedIterScan for F where F:Fn(&str)->Option{type Output=T;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{self(iter.next()?)}}} pub use self::sparse_graph::*; mod sparse_graph{use super::{Adjacencies,AdjacenciesWithEindex,AdjacencyIndex,AdjacencyIndexWithEindex,AdjacencyView,AdjacencyViewIterFromEindex,EIndexedGraph,EdgeMap,EdgeSize,EdgeView,GraphBase,IterScan,MarkedIterScan,VertexMap,VertexSize,VertexView,Vertices};use std::{iter::Cloned,marker::PhantomData,ops,slice};type Marker=PhantomDataT>;#[derive(Clone,Copy,Debug,Eq,PartialEq,Ord,PartialOrd,Hash)]pub enum DirectedEdge{}#[derive(Clone,Copy,Debug,Eq,PartialEq,Ord,PartialOrd,Hash)]pub enum UndirectedEdge{}#[derive(Clone,Copy,Debug,Eq,PartialEq,Ord,PartialOrd,Hash)]pub enum BidirectionalEdge{}#[derive(Clone,Copy,Debug,Default,Eq,PartialEq,Ord,PartialOrd,Hash)]pub struct Adjacency{pub id:usize,pub to:usize}impl Adjacency{pub fn new(id:usize,to:usize)->Adjacency{Adjacency{id,to}}}#[doc=" Static Sparse Graph represented as Compressed Sparse Row."]#[derive(Debug,Clone)]pub struct SparseGraph{vsize:usize,pub start:Vec,pub elist:Vec,pub edges:Vec<(usize,usize)>,_marker:Marker}implSparseGraph{#[doc=" Return the number of vertices."]pub fn vertices_size(&self)->usize{self.vsize}#[doc=" Return the number of edges."]pub fn edges_size(&self)->usize{self.edges.len()}#[doc=" Return an iterator over graph vertices."]pub fn vertices(&self)->ops::Range{0..self.vertices_size()}#[doc=" Return a slice of adjacency vertices."]pub fn adjacencies(&self,v:usize)->slice::Iter<'_,Adjacency>{self.elist[self.start[v]..self.start[v+1]].iter()}pub fn builder(vsize:usize)->SparseGraphBuilder{SparseGraphBuilder::new(vsize)}pub fn builder_with_esize(vsize:usize,esize:usize)->SparseGraphBuilder{SparseGraphBuilder::new_with_esize(vsize,esize)}}pub trait SparseGraphConstruction:Sized{fn construct_graph(vsize:usize,edges:Vec<(usize,usize)>)->SparseGraph;}implSparseGraphwhere D:SparseGraphConstruction{#[doc=" Construct graph from edges."]pub fn from_edges(vsize:usize,edges:Vec<(usize,usize)>)->Self{D::construct_graph(vsize,edges)}pub fn reverse_graph(&self)->SparseGraph{let edges=self.edges.iter().map(|&(from,to)|(to,from)).collect();D::construct_graph(self.vsize,edges)}}impl SparseGraphConstruction for DirectedEdge{fn construct_graph(vsize:usize,edges:Vec<(usize,usize)>)->SparseGraph{let mut start:Vec<_>=vec![0usize;vsize+1];for(from,_)in edges.iter().cloned(){start[from]+=1;}for i in 1..=vsize{start[i]+=start[i-1];}let mut elist=Vec::::with_capacity(edges.len());let ptr=elist.as_mut_ptr();for(id,(from,to))in edges.iter().cloned().enumerate(){start[from]-=1;unsafe{ptr.add(start[from]).write(Adjacency::new(id,to))};}unsafe{elist.set_len(edges.len())};SparseGraph{vsize,start,elist,edges,_marker:PhantomData}}}impl SparseGraphConstruction for UndirectedEdge{fn construct_graph(vsize:usize,edges:Vec<(usize,usize)>)->SparseGraph{let mut start:Vec<_>=vec![0usize;vsize+1];for(from,to)in edges.iter().cloned(){start[to]+=1;start[from]+=1;}for i in 1..=vsize{start[i]+=start[i-1];}let mut elist=Vec::::with_capacity(edges.len()*2);let ptr=elist.as_mut_ptr();for(id,(from,to))in edges.iter().cloned().enumerate(){start[from]-=1;unsafe{ptr.add(start[from]).write(Adjacency::new(id,to))};start[to]-=1;unsafe{ptr.add(start[to]).write(Adjacency::new(id,from))};}unsafe{elist.set_len(edges.len()*2)};SparseGraph{vsize,start,elist,edges,_marker:PhantomData}}}impl SparseGraphConstruction for BidirectionalEdge{fn construct_graph(vsize:usize,edges:Vec<(usize,usize)>)->SparseGraph{let mut start:Vec<_>=vec![0usize;vsize+1];for(from,to)in edges.iter().cloned(){start[to]+=1;start[from]+=1;}for i in 1..=vsize{start[i]+=start[i-1];}let mut elist=Vec::::with_capacity(edges.len()*2);let ptr=elist.as_mut_ptr();for(id,(from,to))in edges.iter().cloned().enumerate(){start[from]-=1;unsafe{ptr.add(start[from]).write(Adjacency::new(id*2,to))};start[to]-=1;unsafe{ptr.add(start[to]).write(Adjacency::new(id*2+1,from))};}unsafe{elist.set_len(edges.len()*2)};SparseGraph{vsize,start,elist,edges,_marker:PhantomData}}}pub type DirectedSparseGraph=SparseGraph;pub type UndirectedSparseGraph=SparseGraph;pub type BidirectionalSparseGraph=SparseGraph;pub struct SparseGraphBuilder{vsize:usize,edges:Vec<(usize,usize)>,rest:Vec,_marker:Marker}implSparseGraphBuilder{pub fn new(vsize:usize)->Self{Self{vsize,edges:Default::default(),rest:Default::default(),_marker:PhantomData}}pub fn new_with_esize(vsize:usize,esize:usize)->Self{Self{vsize,edges:Vec::with_capacity(esize),rest:Vec::with_capacity(esize),_marker:PhantomData}}pub fn add_edge(&mut self,u:usize,v:usize,w:T){self.edges.push((u,v));self.rest.push(w);}}implSparseGraphBuilderwhere D:SparseGraphConstruction{pub fn build(self)->(SparseGraph,Vec){let graph=SparseGraph::from_edges(self.vsize,self.edges);(graph,self.rest)}}pub struct SparseGraphScannerwhere U:IterScan,T:IterScan{vsize:usize,esize:usize,_marker:Marker<(U,T,D)>}implSparseGraphScannerwhere U:IterScan,T:IterScan{pub fn new(vsize:usize,esize:usize)->Self{Self{vsize,esize,_marker:PhantomData}}}implMarkedIterScan for SparseGraphScannerwhere U:IterScan,T:IterScan,D:SparseGraphConstruction{type Output=(SparseGraph,Vec<::Output>);fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{let mut builder=SparseGraphBuilder::new_with_esize(self.vsize,self.esize);for _ in 0..self.esize{builder.add_edge(U::scan(iter)?,U::scan(iter)?,T::scan(iter)?);}Some(builder.build())}}pub type DirectedGraphScanner=SparseGraphScanner;pub type UndirectedGraphScanner=SparseGraphScanner;pub type BidirectionalGraphScanner=SparseGraphScanner;pub struct TreeGraphScannerwhere U:IterScan,T:IterScan{vsize:usize,_marker:Marker<(U,T)>}implTreeGraphScannerwhere U:IterScan,T:IterScan{pub fn new(vsize:usize)->Self{Self{vsize,_marker:PhantomData}}}implMarkedIterScan for TreeGraphScannerwhere U:IterScan,T:IterScan{type Output=(UndirectedSparseGraph,Vec<::Output>);fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{UndirectedGraphScanner::::new(self.vsize,self.vsize-1).mscan(iter)}}implGraphBase for SparseGraph{type VIndex=usize;}implEIndexedGraph for SparseGraph{type EIndex=usize;}implVertexSize for SparseGraph{fn vsize(&self)->usize{self.vsize}}implEdgeSize for SparseGraph{fn esize(&self)->usize{self.edges.len()}}implVertices for SparseGraph{type VIter<'g>=ops::Rangewhere D:'g;fn vertices(&self)->Self::VIter<'_>{0..self.vsize}}implAdjacencies for SparseGraph{type AIndex=Adjacency;type AIter<'g>=Cloned>where D:'g;fn adjacencies(&self,vid:Self::VIndex)->Self::AIter<'_>{self.elist[self.start[vid]..self.start[vid+1]].iter().cloned()}}implAdjacenciesWithEindex for SparseGraph{type AIndex=Adjacency;type AIter<'g>=Cloned>where D:'g;fn adjacencies_with_eindex(&self,vid:Self::VIndex)->Self::AIter<'_>{self.elist[self.start[vid]..self.start[vid+1]].iter().cloned()}}impl AdjacencyIndex for Adjacency{type VIndex=usize;fn vindex(&self)->Self::VIndex{self.to}}impl AdjacencyIndexWithEindex for Adjacency{type EIndex=usize;fn eindex(&self)->Self::EIndex{self.id}}implVertexMapfor SparseGraph{type Vmap=Vec;fn construct_vmap(&self,f:F)->Self::Vmap where F:FnMut()->T{let mut v=Vec::with_capacity(self.vsize);v.resize_with(self.vsize,f);v}fn vmap_get<'a>(&self,map:&'a Self::Vmap,vid:Self::VIndex)->&'a T{assert!(vid(&self,map:&'a mut Self::Vmap,vid:Self::VIndex)->&'a mut T{assert!(vidVertexView,T>for SparseGraphwhere T:Clone{fn vview(&self,map:&Vec,vid:Self::VIndex)->T{self.vmap_get(map,vid).clone()}}implVertexView<[T],T>for SparseGraphwhere T:Clone{fn vview(&self,map:&[T],vid:Self::VIndex)->T{assert!(vidEdgeMapfor SparseGraph{type Emap=Vec;fn construct_emap(&self,f:F)->Self::Emap where F:FnMut()->T{let mut v=Vec::with_capacity(self.vsize);v.resize_with(self.vsize,f);v}fn emap_get<'a>(&self,map:&'a Self::Emap,eid:Self::EIndex)->&'a T{let esize=self.edges.len();assert!(eid(&self,map:&'a mut Self::Emap,eid:Self::EIndex)->&'a mut T{let esize=self.edges.len();assert!(eidEdgeView,T>for SparseGraphwhere T:Clone{fn eview(&self,map:&Vec,eid:Self::EIndex)->T{self.emap_get(map,eid).clone()}}implEdgeView<[T],T>for SparseGraphwhere T:Clone{fn eview(&self,map:&[T],eid:Self::EIndex)->T{let esize=self.edges.len();assert!(eidAdjacencyView<'a,M,T>for SparseGraphwhere Self:AdjacenciesWithEindex+EdgeView,T:Clone,M:'a{type AViewIter<'g>=AdjacencyViewIterFromEindex<'g,'a,Self,M,T>where D:'g;fn aviews<'g>(&'g self,map:&'a M,vid:Self::VIndex)->Self::AViewIter<'g>{AdjacencyViewIterFromEindex::new(self.adjacencies_with_eindex(vid),self,map)}}} pub use self::graph_base::*; mod graph_base{use std::marker::PhantomData;pub trait GraphBase{type VIndex:Copy+Eq;}pub trait EIndexedGraph:GraphBase{type EIndex:Copy+Eq;}pub trait VertexSize:GraphBase{fn vsize(&self)->usize;}pub trait EdgeSize:GraphBase{fn esize(&self)->usize;}pub trait Vertices:GraphBase{type VIter<'g>:Iteratorwhere Self:'g;fn vertices(&self)->Self::VIter<'_>;}pub trait Edges:EIndexedGraph{type EIter<'g>:Iteratorwhere Self:'g;fn edges<'g>(&self)->Self::EIter<'g>;}pub trait AdjacencyIndex{type VIndex:Copy+Eq;fn vindex(&self)->Self::VIndex;}pub trait Adjacencies:GraphBase{type AIndex:AdjacencyIndex;type AIter<'g>:Iteratorwhere Self:'g;fn adjacencies(&self,vid:Self::VIndex)->Self::AIter<'_>;}pub trait AdjacenciesWithEindex:EIndexedGraph{type AIndex:AdjacencyIndexWithEindex;type AIter<'g>:Iteratorwhere Self:'g;fn adjacencies_with_eindex(&self,vid:Self::VIndex)->Self::AIter<'_>;}pub trait AdjacencyIndexWithEindex:AdjacencyIndex{type EIndex:Copy+Eq;fn eindex(&self)->Self::EIndex;}pub trait AdjacencyIndexWithValue:AdjacencyIndex{type AValue:Clone;fn avalue(&self)->Self::AValue;}pub trait AdjacenciesWithValue:GraphBase where T:Clone{type AIndex:AdjacencyIndexWithValue;type AIter<'g>:Iteratorwhere Self:'g;fn adjacencies_with_value(&self,vid:Self::VIndex)->Self::AIter<'_>;}impl AdjacencyIndex for usize{type VIndex=usize;fn vindex(&self)->Self::VIndex{*self}}implAdjacencyIndex for(V,E)where V:Copy+Eq,E:Copy+Eq{type VIndex=V;fn vindex(&self)->Self::VIndex{self.0}}implAdjacencyIndexWithEindex for(V,E)where V:Copy+Eq,E:Copy+Eq{type EIndex=E;fn eindex(&self)->Self::EIndex{self.1}}#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash)]pub struct VIndex(V);#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash)]pub struct VIndexWithEIndex(V,E);#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash)]pub struct VIndexWithValue(V,T);#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash)]pub struct VIndexWithEIndexValue(V,E,T);implAdjacencyIndex for VIndexwhere V:Eq+Copy{type VIndex=V;fn vindex(&self)->Self::VIndex{self.0}}implAdjacencyIndex for VIndexWithEIndexwhere V:Eq+Copy{type VIndex=V;fn vindex(&self)->Self::VIndex{self.0}}implAdjacencyIndexWithEindex for VIndexWithEIndexwhere V:Eq+Copy,E:Eq+Copy{type EIndex=E;fn eindex(&self)->Self::EIndex{self.1}}implAdjacencyIndex for VIndexWithValuewhere V:Eq+Copy{type VIndex=V;fn vindex(&self)->Self::VIndex{self.0}}implAdjacencyIndexWithValue for VIndexWithValuewhere V:Eq+Copy,T:Clone{type AValue=T;fn avalue(&self)->Self::AValue{self.1 .clone()}}implAdjacencyIndex for VIndexWithEIndexValuewhere V:Eq+Copy{type VIndex=V;fn vindex(&self)->Self::VIndex{self.0}}implAdjacencyIndexWithEindex for VIndexWithEIndexValuewhere V:Eq+Copy,E:Eq+Copy{type EIndex=E;fn eindex(&self)->Self::EIndex{self.1}}implAdjacencyIndexWithValue for VIndexWithEIndexValuewhere V:Eq+Copy,T:Clone{type AValue=T;fn avalue(&self)->Self::AValue{self.2 .clone()}}implFromfor VIndex{fn from(vid:V)->Self{VIndex(vid)}}implFrom<(V,E)>for VIndexWithEIndex{fn from((vid,eid):(V,E))->Self{VIndexWithEIndex(vid,eid)}}implFrom<(V,T)>for VIndexWithValue{fn from((vid,value):(V,T))->Self{VIndexWithValue(vid,value)}}implFrom<(V,E,T)>for VIndexWithEIndexValue{fn from((vid,eid,value):(V,E,T))->Self{VIndexWithEIndexValue(vid,eid,value)}}implVIndexWithValue{pub fn map(self,mut f:F)->VIndexWithValuewhere F:FnMut(T)->U{VIndexWithValue(self.0,f(self.1))}}implVIndexWithEIndexValue{pub fn map(self,mut f:F)->VIndexWithEIndexValuewhere F:FnMut(T)->U{VIndexWithEIndexValue(self.0,self.1,f(self.2))}}pub trait VertexMap:GraphBase{type Vmap;fn construct_vmap(&self,f:F)->Self::Vmap where F:FnMut()->T;fn vmap_get<'a>(&self,map:&'a Self::Vmap,vid:Self::VIndex)->&'a T;fn vmap_get_mut<'a>(&self,map:&'a mut Self::Vmap,vid:Self::VIndex)->&'a mut T;fn vmap_set(&self,map:&mut Self::Vmap,vid:Self::VIndex,x:T){*self.vmap_get_mut(map,vid)=x;}}pub trait VertexView:GraphBase where M:?Sized{fn vview(&self,map:&M,vid:Self::VIndex)->T;}pub trait EdgeMap:EIndexedGraph{type Emap;fn construct_emap(&self,f:F)->Self::Emap where F:FnMut()->T;fn emap_get<'a>(&self,map:&'a Self::Emap,eid:Self::EIndex)->&'a T;fn emap_get_mut<'a>(&self,map:&'a mut Self::Emap,eid:Self::EIndex)->&'a mut T;fn emap_set(&self,map:&mut Self::Emap,eid:Self::EIndex,x:T){*self.emap_get_mut(map,eid)=x;}}pub trait EdgeView:EIndexedGraph where M:?Sized{fn eview(&self,map:&M,eid:Self::EIndex)->T;}implVertexViewfor G where G:GraphBase,F:Fn(Self::VIndex)->T{fn vview(&self,map:&F,vid:Self::VIndex)->T{(map)(vid)}}implEdgeViewfor G where G:EIndexedGraph,F:Fn(Self::EIndex)->T{fn eview(&self,map:&F,eid:Self::EIndex)->T{(map)(eid)}}pub trait AdjacencyView<'a,M,T>:GraphBase where M:?Sized{type AViewIter<'g>:Iterator>where M:'a,Self:'g;fn aviews<'g>(&'g self,map:&'a M,vid:Self::VIndex)->Self::AViewIter<'g>;}pub struct AdjacencyViewIterFromEindex<'g,'a,G,M,T>where G:AdjacenciesWithEindex{iter:G::AIter<'g>,g:&'g G,map:&'a M,_marker:PhantomDataT>}impl<'g,'a,G,M,T>AdjacencyViewIterFromEindex<'g,'a,G,M,T>where G:AdjacenciesWithEindex{pub fn new(iter:G::AIter<'g>,g:&'g G,map:&'a M)->Self{Self{iter,g,map,_marker:PhantomData}}}impl<'a,G,M,T>Iterator for AdjacencyViewIterFromEindex<'_,'a,G,M,T>where G:AdjacenciesWithEindex+EdgeView,M:'a{type Item=VIndexWithValue;fn next(&mut self)->Option{self.iter.next().map(|adj|(adj.vindex(),self.g.eview(self.map,adj.eindex())).into())}}pub struct AdjacencyViewIterFromValue<'g,'a,G,M,T,U>where G:'g+AdjacenciesWithValue,T:Clone{iter:G::AIter<'g>,map:&'a M,_marker:PhantomDataU>}impl<'g,'a,G,M,T,U>AdjacencyViewIterFromValue<'g,'a,G,M,T,U>where G:AdjacenciesWithValue,T:Clone{pub fn new(iter:G::AIter<'g>,map:&'a M)->Self{Self{iter,map,_marker:PhantomData}}}impl<'a,G,M,T,U>Iterator for AdjacencyViewIterFromValue<'_,'a,G,M,T,U>where G:AdjacenciesWithValue,T:Clone,M:'a+Fn(T)->U{type Item=VIndexWithValue;fn next(&mut self)->Option{self.iter.next().map(|adj|(adj.vindex(),(self.map)(adj.avalue())).into())}}} pub use self::union_find::{MergingUnionFind,PotentializedUnionFind,UndoableUnionFind,UnionFind,UnionFindBase}; pub mod union_find{use super::{Group,Monoid};use std::{collections::HashMap,fmt::{self,Debug},marker::PhantomData,mem::swap};pub struct UnionFindBasewhere U:UnionStrategy,F:FindStrategy,M:UfMergeSpec,P:Monoid,H:UndoStrategy>{cells:Vec>,merger:M,history:H::History,_marker:PhantomDataF>}implClone for UnionFindBasewhere U:UnionStrategy,F:FindStrategy,M:UfMergeSpec+Clone,P:Monoid,H:UndoStrategy,History:Clone>{fn clone(&self)->Self{Self{cells:self.cells.clone(),merger:self.merger.clone(),history:self.history.clone(),_marker:self._marker}}}implDebug for UnionFindBasewhere U:UnionStrategy,F:FindStrategy,M:UfMergeSpec,P:Monoid,H:UndoStrategy,History:Debug>{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{f.debug_struct("UnionFindBase").field("cells",&self.cells).field("history",&self.history).finish()}}pub enum UfCellwhere U:UnionStrategy,M:UfMergeSpec,P:Monoid{Root((U::Info,M::Data)),Child((usize,P::T))}implClone for UfCellwhere U:UnionStrategy,M:UfMergeSpec,P:Monoid{fn clone(&self)->Self{match self{Self::Root(data)=>Self::Root(data.clone()),Self::Child(data)=>Self::Child(data.clone()),}}}implDebug for UfCellwhere U:UnionStrategy,M:UfMergeSpec,P:Monoid{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{match self{Self::Root(data)=>f.debug_tuple("Root").field(data).finish(),Self::Child(data)=>f.debug_tuple("Child").field(data).finish(),}}}implUfCellwhere U:UnionStrategy,M:UfMergeSpec,P:Monoid{fn root_mut(&mut self)->Option<&mut(U::Info,M::Data)>{match self{UfCell::Root(root)=>Some(root),UfCell::Child(_)=>None,}}fn child_mut(&mut self)->Option<&mut(usize,P::T)>{match self{UfCell::Child(child)=>Some(child),UfCell::Root(_)=>None,}}}pub trait FindStrategy{const CHENGE_ROOT:bool;}pub enum PathCompression{}impl FindStrategy for PathCompression{const CHENGE_ROOT:bool=true;}impl FindStrategy for(){const CHENGE_ROOT:bool=false;}pub trait UnionStrategy{type Info:Clone;fn single_info()->Self::Info;fn check_directoin(parent:&Self::Info,child:&Self::Info)->bool;fn unite(parent:&Self::Info,child:&Self::Info)->Self::Info;}pub enum UnionBySize{}impl UnionStrategy for UnionBySize{type Info=usize;fn single_info()->Self::Info{1}fn check_directoin(parent:&Self::Info,child:&Self::Info)->bool{parent>=child}fn unite(parent:&Self::Info,child:&Self::Info)->Self::Info{parent+child}}pub enum UnionByRank{}impl UnionStrategy for UnionByRank{type Info=u32;fn single_info()->Self::Info{0}fn check_directoin(parent:&Self::Info,child:&Self::Info)->bool{parent>=child}fn unite(parent:&Self::Info,child:&Self::Info)->Self::Info{parent+(parent==child)as u32}}impl UnionStrategy for(){type Info=();fn single_info()->Self::Info{}fn check_directoin(_parent:&Self::Info,_child:&Self::Info)->bool{false}fn unite(_parent:&Self::Info,_child:&Self::Info)->Self::Info{}}pub trait UfMergeSpec{type Data;fn merge(&mut self,to:&mut Self::Data,from:&mut Self::Data);}#[derive(Debug,Clone)]pub struct FnMerger{f:F,_marker:PhantomDataT>}implUfMergeSpec for FnMergerwhere F:FnMut(&mut T,&mut T){type Data=T;fn merge(&mut self,to:&mut Self::Data,from:&mut Self::Data){(self.f)(to,from)}}impl UfMergeSpec for(){type Data=();fn merge(&mut self,_to:&mut Self::Data,_from:&mut Self::Data){}}pub trait UndoStrategy{const UNDOABLE:bool;type History:Default;fn unite(history:&mut Self::History,x:usize,y:usize,cells:&[T]);fn undo_unite(history:&mut Self::History,cells:&mut[T]);}pub enum Undoable{}implUndoStrategyfor Undoable where T:Clone{const UNDOABLE:bool=true;type History=Vec<[(usize,T);2]>;fn unite(history:&mut Self::History,x:usize,y:usize,cells:&[T]){let cx=cells[x].clone();let cy=cells[y].clone();history.push([(x,cx),(y,cy)]);}fn undo_unite(history:&mut Self::History,cells:&mut[T]){if let Some([(x,cx),(y,cy)])=history.pop(){cells[x]=cx;cells[y]=cy;}}}implUndoStrategyfor(){const UNDOABLE:bool=false;type History=();fn unite(_history:&mut Self::History,_x:usize,_y:usize,_cells:&[T]){}fn undo_unite(_history:&mut Self::History,_cells:&mut[T]){}}implUnionFindBasewhere U:UnionStrategy,F:FindStrategy,P:Monoid,H:UndoStrategy>{pub fn new(n:usize)->Self{let cells:Vec<_>=(0..n).map(|_|UfCell::Root((U::single_info(),()))).collect();Self{cells,merger:(),history:Default::default(),_marker:PhantomData}}pub fn push(&mut self){self.cells.push(UfCell::Root((U::single_info(),())));}}implUnionFindBase,P,H>where U:UnionStrategy,F:FindStrategy,Merge:FnMut(&mut T,&mut T),P:Monoid,H:UndoStrategy,P>>{pub fn new_with_merger(n:usize,mut init:impl FnMut(usize)->T,merge:Merge)->Self{let cells:Vec<_>=(0..n).map(|i|UfCell::Root((U::single_info(),init(i)))).collect();Self{cells,merger:FnMerger{f:merge,_marker:PhantomData},history:Default::default(),_marker:PhantomData}}}implUnionFindBasewhere F:FindStrategy,M:UfMergeSpec,P:Monoid,H:UndoStrategy>{pub fn size(&mut self,x:usize)->::Info{let root=self.find_root(x);self.root_info(root).unwrap()}}implUnionFindBasewhere U:UnionStrategy,F:FindStrategy,M:UfMergeSpec,P:Monoid,H:UndoStrategy>{fn root_info(&mut self,x:usize)->Option{match&self.cells[x]{UfCell::Root((info,_))=>Some(info.clone()),UfCell::Child(_)=>None,}}fn root_info_mut(&mut self,x:usize)->Option<&mut U::Info>{match&mut self.cells[x]{UfCell::Root((info,_))=>Some(info),UfCell::Child(_)=>None,}}pub fn same(&mut self,x:usize,y:usize)->bool{self.find_root(x)==self.find_root(y)}pub fn merge_data(&mut self,x:usize)->&M::Data{let root=self.find_root(x);match&self.cells[root]{UfCell::Root((_,data))=>data,UfCell::Child(_)=>unreachable!(),}}pub fn merge_data_mut(&mut self,x:usize)->&mut M::Data{let root=self.find_root(x);match&mut self.cells[root]{UfCell::Root((_,data))=>data,UfCell::Child(_)=>unreachable!(),}}pub fn roots(&self)->impl Iterator+'_{(0..self.cells.len()).filter(|&x|matches!(self.cells[x],UfCell::Root(_)))}pub fn all_group_members(&mut self)->HashMap>{let mut groups_map=HashMap::new();for x in 0..self.cells.len(){let r=self.find_root(x);groups_map.entry(r).or_insert_with(Vec::new).push(x);}groups_map}pub fn find(&mut self,x:usize)->(usize,P::T){let(parent_parent,parent_potential)=match&self.cells[x]{UfCell::Child((parent,_))=>self.find(*parent),UfCell::Root(_)=>return(x,P::unit()),};let(parent,potential)=self.cells[x].child_mut().unwrap();let potential=if F::CHENGE_ROOT{*parent=parent_parent;*potential=P::operate(&parent_potential,potential);potential.clone()}else{P::operate(&parent_potential,potential)};(parent_parent,potential)}pub fn find_root(&mut self,x:usize)->usize{let(parent,parent_parent)=match&self.cells[x]{UfCell::Child((parent,_))=>(*parent,self.find_root(*parent)),UfCell::Root(_)=>return x,};if F::CHENGE_ROOT{let(cx,cp)={let ptr=self.cells.as_mut_ptr();unsafe{(&mut*ptr.add(x),&*ptr.add(parent))}};let(parent,potential)=cx.child_mut().unwrap();*parent=parent_parent;if let UfCell::Child((_,ppot))=&cp{*potential=P::operate(ppot,potential);}}parent_parent}pub fn unite_noninv(&mut self,x:usize,y:usize,potential:P::T)->bool{let(rx,potx)=self.find(x);let ry=self.find_root(y);if rx==ry||y!=ry{return false;}H::unite(&mut self.history,rx,ry,&self.cells);{let ptr=self.cells.as_mut_ptr();let(cx,cy)=unsafe{(&mut*ptr.add(rx),&mut*ptr.add(ry))};self.merger.merge(&mut cx.root_mut().unwrap().1,&mut cy.root_mut().unwrap().1);}*self.root_info_mut(rx).unwrap()=U::unite(&self.root_info(rx).unwrap(),&self.root_info(ry).unwrap());self.cells[ry]=UfCell::Child((rx,P::operate(&potx,&potential)));true}}implUnionFindBasewhere U:UnionStrategy,F:FindStrategy,M:UfMergeSpec,P:Group,H:UndoStrategy>{pub fn difference(&mut self,x:usize,y:usize)->Option{let(rx,potx)=self.find(x);let(ry,poty)=self.find(y);if rx==ry{Some(P::operate(&P::inverse(&potx),&poty))}else{None}}pub fn unite_with(&mut self,x:usize,y:usize,potential:P::T)->bool{let(mut rx,potx)=self.find(x);let(mut ry,poty)=self.find(y);if rx==ry{return false;}let mut xinfo=self.root_info(rx).unwrap();let mut yinfo=self.root_info(ry).unwrap();let inverse=!U::check_directoin(&xinfo,&yinfo);let potential=if inverse{P::rinv_operate(&poty,&P::operate(&potx,&potential))}else{P::operate(&potx,&P::rinv_operate(&potential,&poty))};if inverse{swap(&mut rx,&mut ry);swap(&mut xinfo,&mut yinfo);}H::unite(&mut self.history,rx,ry,&self.cells);{let ptr=self.cells.as_mut_ptr();let(cx,cy)=unsafe{(&mut*ptr.add(rx),&mut*ptr.add(ry))};self.merger.merge(&mut cx.root_mut().unwrap().1,&mut cy.root_mut().unwrap().1);}*self.root_info_mut(rx).unwrap()=U::unite(&xinfo,&yinfo);self.cells[ry]=UfCell::Child((rx,potential));true}pub fn unite(&mut self,x:usize,y:usize)->bool{self.unite_with(x,y,P::unit())}}implUnionFindBasewhere U:UnionStrategy,M:UfMergeSpec,P:Monoid,H:UndoStrategy>{pub fn undo(&mut self){H::undo_unite(&mut self.history,&mut self.cells);}}pub type UnionFind=UnionFindBase;pub type MergingUnionFind=UnionFindBase,(),()>;pub type PotentializedUnionFind

=UnionFindBase;pub type UndoableUnionFind=UnionFindBase;} mod tuple_operation_impl{use super::*;macro_rules!impl_tuple_operation{(@impl)=>{impl Magma for(){type T=();fn operate(_x:&Self::T,_y:&Self::T)->Self::T{}}impl Unital for(){fn unit()->Self::T{}}impl Associative for(){}impl Commutative for(){}impl Idempotent for(){}impl Invertible for(){fn inverse(_x:&Self::T)->Self::T{}}};(@impl$($T:ident$i:tt)*)=>{impl<$($T:Magma),*>Magma for($($T,)*){type T=($(<$T as Magma>::T,)*);fn operate(x:&Self::T,y:&Self::T)->Self::T{($(<$T as Magma>::operate(&x.$i,&y.$i),)*)}}impl<$($T:Unital),*>Unital for($($T,)*){fn unit()->Self::T{($(<$T as Unital>::unit(),)*)}}impl<$($T:Associative),*>Associative for($($T,)*){}impl<$($T:Commutative),*>Commutative for($($T,)*){}impl<$($T:Idempotent),*>Idempotent for($($T,)*){}impl<$($T:Invertible),*>Invertible for($($T,)*){fn inverse(x:&Self::T)->Self::T{($(<$T as Invertible>::inverse(&x.$i),)*)}}};(@inner$($T:ident$i:tt)*;$U:ident$j:tt$($t:tt)*)=>{impl_tuple_operation!(@impl$($T$i)*);impl_tuple_operation!(@inner$($T$i)*$U$j;$($t)*);};(@inner$($T:ident$i:tt)*;)=>{impl_tuple_operation!(@impl$($T$i)*);};($($t:tt)*)=>{impl_tuple_operation!(@inner;$($t)*);};}impl_tuple_operation!(A 0 B 1 C 2 D 3 E 4 F 5 G 6 H 7 I 8 J 9);} pub use self::magma::*; 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{#[cfg(test)]fn check_associative(a:&Self::T,b:&Self::T,c:&Self::T)->bool where Self::T:PartialEq{({let ab_c=Self::operate(&Self::operate(a,b),c);let a_bc=Self::operate(a,&Self::operate(b,c));ab_c==a_bc})&&({let ab_c=Self::reverse_operate(c,&Self::reverse_operate(b,a));let a_bc=Self::reverse_operate(&Self::reverse_operate(c,b),a);ab_c==a_bc})&&({let mut ab_c=a.clone();Self::operate_assign(&mut ab_c,b);Self::operate_assign(&mut ab_c,c);let mut bc=b.clone();Self::operate_assign(&mut bc,c);let mut a_bc=a.clone();Self::operate_assign(&mut a_bc,&bc);ab_c==a_bc})}}#[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 = e$"]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();}#[cfg(test)]fn check_unital(x:&Self::T)->bool where Self::T:PartialEq{let u=Self::unit();let xu=Self::operate(x,&u);let ux=Self::operate(&u,x);let mut any=x.clone();Self::set_unit(&mut any);xu==*x&&ux==*x&&Self::is_unit(&u)&&Self::is_unit(&any)}}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 res=Self::unit();for bit in exp.bits(){if bit{res=Self::operate(&res,&x);}x=Self::operate(&x,&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);}#[cfg(test)]fn check_invertible(x:&Self::T)->bool where Self::T:PartialEq{let i=Self::inverse(x);({let xi=Self::operate(x,&i);let ix=Self::operate(&i,x);Self::is_unit(&xi)&&Self::is_unit(&ix)})&&({let ii=Self::inverse(&i);ii==*x})&&({let mut xi=x.clone();Self::operate_assign(&mut xi,&i);let mut ix=i.clone();Self::operate_assign(&mut ix,x);Self::is_unit(&xi)&&Self::is_unit(&ix)})&&({let mut xi=x.clone();Self::rinv_operate_assign(&mut xi,x);let mut ix=i.clone();Self::rinv_operate_assign(&mut ix,&i);Self::is_unit(&xi)&&Self::is_unit(&ix)})}}#[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{#[cfg(test)]fn check_commutative(a:&Self::T,b:&Self::T)->bool where Self::T:PartialEq{Self::operate(a,b)==Self::operate(b,a)}}#[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{#[cfg(test)]fn check_idempotent(a:&Self::T)->bool where Self::T:PartialEq{Self::operate(a,a)==*a}}#[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{}};}} pub use self::strongly_connected_component::StronglyConnectedComponent; mod strongly_connected_component{use super::DirectedSparseGraph;#[derive(Debug,Clone)]pub struct StronglyConnectedComponent<'a>{graph:&'a DirectedSparseGraph,visited:Vec,csize:usize,low:Vec,ord:Vec,comp:Vec}impl std::ops::Indexfor StronglyConnectedComponent<'_>{type Output=usize;fn index(&self,index:usize)->&Self::Output{&self.comp[index]}}impl<'a>StronglyConnectedComponent<'a>{pub fn new(graph:&'a DirectedSparseGraph)->Self{let mut now_ord=0;let mut self_=Self{graph,csize:0,visited:Vec::with_capacity(graph.vertices_size()),low:vec![0;graph.vertices_size()],ord:vec![usize::MAX;graph.vertices_size()],comp:vec![0;graph.vertices_size()]};for u in graph.vertices(){if self_.ord[u]==usize::MAX{self_.dfs(u,&mut now_ord);}}for x in self_.comp.iter_mut(){*x=self_.csize-1-*x;}self_}}impl StronglyConnectedComponent<'_>{fn dfs(&mut self,u:usize,now_ord:&mut usize){self.low[u]=*now_ord;self.ord[u]=*now_ord;*now_ord+=1;self.visited.push(u);for a in self.graph.adjacencies(u){if self.ord[a.to]==usize::MAX{self.dfs(a.to,now_ord);self.low[u]=self.low[u].min(self.low[a.to]);}else{self.low[u]=self.low[u].min(self.ord[a.to]);}}if self.low[u]==self.ord[u]{while let Some(v)=self.visited.pop(){self.ord[v]=self.graph.vertices_size();self.comp[v]=self.csize;if v==u{break;}}self.csize+=1;}}pub fn gen_cgraph(&self)->DirectedSparseGraph{let mut used=std::collections::HashSet::new();let mut edges=vec![];for u in self.graph.vertices(){for a in self.graph.adjacencies(u){if self.comp[u]!=self.comp[a.to]{let(x,y)=(self.comp[u],self.comp[a.to]);if!used.contains(&(x,y)){used.insert((x,y));edges.push((x,y));}}}}DirectedSparseGraph::from_edges(self.size(),edges)}pub fn components(&self)->Vec>{let mut counts=vec![0;self.size()];for&x in self.comp.iter(){counts[x]+=1;}let mut groups=vec![vec![];self.size()];for(g,c)in groups.iter_mut().zip(counts){g.reserve(c);}for u in self.graph.vertices(){groups[self[u]].push(u);}groups}pub fn has_loop(&self)->bool{self.graph.vertices_size()!=self.csize}pub fn size(&self)->usize{self.csize}}} mod topological_sort{use super::SparseGraph;implSparseGraph{pub fn topological_sort(&self)->Vec{let mut indeg=vec![0;self.vertices_size()];let mut res=vec![];for a in self.vertices().flat_map(|u|self.adjacencies(u)){indeg[a.to]+=1;}let mut stack=self.vertices().filter(|&u|indeg[u]==0).collect::>();while let Some(u)=stack.pop(){res.push(u);for a in self.adjacencies(u){indeg[a.to]-=1;if indeg[a.to]==0{stack.push(a.to);}}}res}}}