結果

問題 No.2292 Interval Union Find
ユーザー to-omerto-omer
提出日時 2023-05-05 23:36:13
言語 Rust
(1.77.0 + proconio)
結果
AC  
実行時間 210 ms / 5,000 ms
コード長 33,556 bytes
コンパイル時間 25,847 ms
コンパイル使用メモリ 379,060 KB
実行使用メモリ 12,928 KB
最終ジャッジ日時 2024-05-02 18:56:22
合計ジャッジ時間 24,498 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
5,248 KB
testcase_01 AC 2 ms
5,248 KB
testcase_02 AC 1 ms
5,248 KB
testcase_03 AC 2 ms
5,376 KB
testcase_04 AC 131 ms
5,376 KB
testcase_05 AC 123 ms
5,376 KB
testcase_06 AC 80 ms
5,376 KB
testcase_07 AC 118 ms
5,376 KB
testcase_08 AC 148 ms
5,760 KB
testcase_09 AC 113 ms
5,760 KB
testcase_10 AC 129 ms
5,760 KB
testcase_11 AC 113 ms
5,760 KB
testcase_12 AC 105 ms
5,632 KB
testcase_13 AC 50 ms
5,760 KB
testcase_14 AC 47 ms
5,760 KB
testcase_15 AC 54 ms
5,888 KB
testcase_16 AC 46 ms
5,760 KB
testcase_17 AC 71 ms
5,760 KB
testcase_18 AC 146 ms
12,928 KB
testcase_19 AC 183 ms
11,776 KB
testcase_20 AC 210 ms
11,776 KB
testcase_21 AC 160 ms
9,216 KB
testcase_22 AC 161 ms
9,216 KB
testcase_23 AC 162 ms
9,088 KB
testcase_24 AC 167 ms
9,216 KB
testcase_25 AC 159 ms
9,216 KB
testcase_26 AC 162 ms
9,344 KB
testcase_27 AC 160 ms
9,216 KB
testcase_28 AC 160 ms
9,216 KB
testcase_29 AC 163 ms
9,088 KB
testcase_30 AC 161 ms
9,344 KB
testcase_31 AC 160 ms
9,216 KB
testcase_32 AC 168 ms
9,216 KB
testcase_33 AC 162 ms
9,216 KB
testcase_34 AC 170 ms
9,344 KB
testcase_35 AC 159 ms
9,216 KB
testcase_36 AC 159 ms
9,216 KB
testcase_37 AC 163 ms
9,216 KB
testcase_38 AC 164 ms
9,216 KB
testcase_39 AC 164 ms
9,088 KB
testcase_40 AC 165 ms
9,216 KB
testcase_41 AC 24 ms
5,376 KB
testcase_42 AC 25 ms
5,376 KB
testcase_43 AC 28 ms
5,376 KB
testcase_44 AC 34 ms
5,376 KB
testcase_45 AC 34 ms
5,376 KB
testcase_46 AC 37 ms
5,376 KB
testcase_47 AC 43 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

pub fn solve() {
    crate::prepare!();
    sc!(_n, q);
    let mut s = RangeSet::new();
    for _ in 0..q {
        match sv!(usize) {
            1 => {
                sc!(l, r);
                s.insert((l, r));
            }
            2 => {
                sc!(l, r);
                s.remove((l, r));
            }
            3 => {
                sc!(u, v);
                let ans = u == v
                    || s.get_range(&u)
                        .or_else(|| s.get_range(&(u - 1)))
                        .map_or(false, |&(l, r)| {
                            (l..=r).contains(&u) && (l..=r).contains(&v)
                        });
                pp!(ans as usize);
            }
            _ => {
                sc!(u);
                let ans = s
                    .get_range(&u)
                    .or_else(|| s.get_range(&(u - 1)))
                    .map(|(l, r)| r - l)
                    .unwrap_or_default()
                    + 1;
                pp!(ans);
            }
        }
    }
}
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]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)*)}}};()=>{$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<W,S>(self,writer:&mut W,sep:S,is_head:bool)->Result<(),Error>where W:Write,S:Display;}macro_rules!iter_print_tuple_impl{(@impl$($A:ident$a:ident)?,$($B:ident$b:ident)*)=>{impl<$($A,)?$($B),*>IterPrint for($($A,)?$($B),*)where$($A:Display,)?$($B:Display),*{#[allow(unused_variables)]fn iter_print<W,S>(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)*)=>{iter_print_tuple_impl!(@impl,);iter_print_tuple_impl!(@inc$C$c,,$($D$d)*);};(@inc$A:ident$a:ident,$($B:ident$b:ident)*,$C:ident$c:ident$($D:ident$d:ident)*)=>{iter_print_tuple_impl!(@impl$A$a,$($B$b)*);iter_print_tuple_impl!(@inc$A$a,$($B$b)*$C$c,$($D$d)*);};(@inc$A:ident$a:ident,$($B:ident$b:ident)*,)=>{iter_print_tuple_impl!(@impl$A$a,$($B$b)*);};($($t:tt)*)=>{iter_print_tuple_impl!(@inc,,$($t)*);};}iter_print_tuple_impl!(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};const LEN:usize=$len;let mut$data:[MaybeUninit<_>;LEN]=unsafe{MaybeUninit::uninit().assume_init()};$init;#[repr(C)]union __Transmuter<T:Copy>{src:ManuallyDrop<[MaybeUninit<T>;LEN]>,dst:ManuallyDrop<[T;LEN]>,}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::{from_fn,repeat_with,FromIterator},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<Item=&'a str>>(iter:&mut I)->Option<Self::Output>;}pub trait MarkedIterScan:Sized{type Output;fn mscan<'a,I:Iterator<Item=&'a str>>(self,iter:&mut I)->Option<Self::Output>;}#[derive(Clone,Debug)]pub struct Scanner<'a>{iter:std::str::SplitAsciiWhitespace<'a>}impl<'a>Scanner<'a>{#[inline]pub fn new(s:&'a str)->Self{let iter=s.split_ascii_whitespace();Self{iter}}#[inline]pub fn scan<T>(&mut self)-><T as IterScan>::Output where T:IterScan{<T as IterScan>::scan(&mut self.iter).expect("scan error")}#[inline]pub fn mscan<T>(&mut self,marker:T)-><T as MarkedIterScan>::Output where T:MarkedIterScan{marker.mscan(&mut self.iter).expect("scan error")}#[inline]pub fn scan_vec<T>(&mut self,size:usize)->Vec<<T as IterScan>::Output>where T:IterScan{(0..size).map(|_|<T as IterScan>::scan(&mut self.iter).expect("scan error")).collect()}#[inline]pub fn iter<'b,T>(&'b mut self)->ScannerIter<'a,'b,T>where T:IterScan{ScannerIter{inner:self,_marker:std::marker::PhantomData}}}macro_rules!iter_scan_impls{($($t:ty)*)=>{$(impl IterScan for$t{type Output=Self;#[inline]fn scan<'a,I:Iterator<Item=&'a str>>(iter:&mut I)->Option<Self>{iter.next()?.parse::<$t>().ok()}})*};}iter_scan_impls!(char u8 u16 u32 u64 usize i8 i16 i32 i64 isize f32 f64 u128 i128 String);macro_rules!iter_scan_tuple_impl{(@impl$($T:ident)*)=>{impl<$($T:IterScan),*>IterScan for($($T,)*){type Output=($(<$T as IterScan>::Output,)*);#[inline]fn scan<'a,It:Iterator<Item=&'a str>>(_iter:&mut It)->Option<Self::Output>{Some(($(<$T as IterScan>::scan(_iter)?,)*))}}};(@inner$($T:ident)*,)=>{iter_scan_tuple_impl!(@impl$($T)*);};(@inner$($T:ident)*,$U:ident$($Rest:ident)*)=>{iter_scan_tuple_impl!(@impl$($T)*);iter_scan_tuple_impl!(@inner$($T)*$U,$($Rest)*);};($($T:ident)*)=>{iter_scan_tuple_impl!(@inner,$($T)*);};}iter_scan_tuple_impl!(A B C D E F G H I J K);pub struct ScannerIter<'a,'b,T>{inner:&'b mut Scanner<'a>,_marker:std::marker::PhantomData<fn()->T>}impl<'a,'b,T>Iterator for ScannerIter<'a,'b,T>where T:IterScan{type Item=<T as IterScan>::Output;#[inline]fn next(&mut self)->Option<Self::Item>{<T as IterScan>::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=" - `[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::<Vec<_>>())?};(@array$scanner:expr,[$($t:tt)*]$len:expr)=>{$crate::array![||$crate::scan_value!(@inner$scanner,[]$($t)*);$len]};(@tuple$scanner:expr,[$([$($args:tt)*])*])=>{($($($args)*,)*)};(@$tag:ident$scanner:expr,[[$($args:tt)*]])=>{$($args)*};(@$tag:ident$scanner:expr,[$($args:tt)*]@$e:expr)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$scanner.mscan($e)]])};(@$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)*][@$e:expr;const$len:expr]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@array$scanner,[@$e]$len)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][@$e:expr;$len:expr]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@repeat$scanner,[@$e]$len)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][[$($tt:tt)*];const$len:expr]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@array$scanner,[[$($tt)*]]$len)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][[$($tt:tt)*];$len:expr]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@repeat$scanner,[[$($tt)*]]$len)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][($($tt:tt)*);const$len:expr]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@array$scanner,[($($tt)*)]$len)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][($($tt:tt)*);$len:expr]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@repeat$scanner,[($($tt)*)]$len)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][$ty:ty;const$len:expr]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@array$scanner,[$ty]$len)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][$ty:ty;$len:expr]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@repeat$scanner,[$ty]$len)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][$($tt:tt)*]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@repeat$scanner,[$($tt)*])]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*]$ty:ty)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$scanner.scan::<$ty>()]])};(@$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)*))};($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)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*@$e])};(@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)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*$ty])};(@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)*)};($scanner:expr,$($t:tt)*)=>{$crate::scan!(@pat$scanner,[][]$($t)*)}}#[derive(Debug,Copy,Clone)]pub enum Usize1{}impl IterScan for Usize1{type Output=usize;#[inline]fn scan<'a,I:Iterator<Item=&'a str>>(iter:&mut I)->Option<Self::Output>{<usize as IterScan>::scan(iter)?.checked_sub(1)}}#[derive(Debug,Copy,Clone)]pub struct CharWithBase(pub char);impl MarkedIterScan for CharWithBase{type Output=usize;#[inline]fn mscan<'a,I:Iterator<Item=&'a str>>(self,iter:&mut I)->Option<Self::Output>{Some((<char as IterScan>::scan(iter)?as u8-self.0 as u8)as usize)}}#[derive(Debug,Copy,Clone)]pub enum Chars{}impl IterScan for Chars{type Output=Vec<char>;#[inline]fn scan<'a,I:Iterator<Item=&'a str>>(iter:&mut I)->Option<Self::Output>{Some(iter.next()?.chars().collect())}}#[derive(Debug,Copy,Clone)]pub struct CharsWithBase(pub char);impl MarkedIterScan for CharsWithBase{type Output=Vec<usize>;#[inline]fn mscan<'a,I:Iterator<Item=&'a str>>(self,iter:&mut I)->Option<Self::Output>{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;#[inline]fn scan<'a,I:Iterator<Item=&'a str>>(iter:&mut I)->Option<Self::Output>{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;#[inline]fn mscan<'a,I:Iterator<Item=&'a str>>(self,iter:&mut I)->Option<Self::Output>{Some((<char as IterScan>::scan(iter)?as u8-self.0)as usize)}}#[derive(Debug,Copy,Clone)]pub enum Bytes{}impl IterScan for Bytes{type Output=Vec<u8>;#[inline]fn scan<'a,I:Iterator<Item=&'a str>>(iter:&mut I)->Option<Self::Output>{Some(iter.next()?.bytes().collect())}}#[derive(Debug,Copy,Clone)]pub struct BytesWithBase(pub u8);impl MarkedIterScan for BytesWithBase{type Output=Vec<usize>;#[inline]fn mscan<'a,I:Iterator<Item=&'a str>>(self,iter:&mut I)->Option<Self::Output>{Some(iter.next()?.bytes().map(|c|(c-self.0)as usize).collect())}}#[derive(Debug,Copy,Clone)]pub struct Collect<T,B=Vec<<T as IterScan>::Output>>where T:IterScan,B:FromIterator<<T as IterScan>::Output>{size:usize,_marker:PhantomData<fn()->(T,B)>}impl<T,B>Collect<T,B>where T:IterScan,B:FromIterator<<T as IterScan>::Output>{pub fn new(size:usize)->Self{Self{size,_marker:PhantomData}}}impl<T,B>MarkedIterScan for Collect<T,B>where T:IterScan,B:FromIterator<<T as IterScan>::Output>{type Output=B;#[inline]fn mscan<'a,I:Iterator<Item=&'a str>>(self,iter:&mut I)->Option<Self::Output>{repeat_with(||<T as IterScan>::scan(iter)).take(self.size).collect()}}#[derive(Debug,Copy,Clone)]pub struct SizedCollect<T,B=Vec<<T as IterScan>::Output>>where T:IterScan,B:FromIterator<<T as IterScan>::Output>{_marker:PhantomData<fn()->(T,B)>}impl<T,B>IterScan for SizedCollect<T,B>where T:IterScan,B:FromIterator<<T as IterScan>::Output>{type Output=B;#[inline]fn scan<'a,I:Iterator<Item=&'a str>>(iter:&mut I)->Option<Self::Output>{let size=usize::scan(iter)?;repeat_with(||<T as IterScan>::scan(iter)).take(size).collect()}}#[derive(Debug,Copy,Clone)]pub struct Splitted<T,P>where T:IterScan{pat:P,_marker:PhantomData<fn()->T>}impl<T,P>Splitted<T,P>where T:IterScan{pub fn new(pat:P)->Self{Self{pat,_marker:PhantomData}}}impl<T>MarkedIterScan for Splitted<T,char>where T:IterScan{type Output=Vec<<T as IterScan>::Output>;fn mscan<'a,I:Iterator<Item=&'a str>>(self,iter:&mut I)->Option<Self::Output>{let mut iter=iter.next()?.split(self.pat);Some(from_fn(||<T as IterScan>::scan(&mut iter)).collect())}}impl<T>MarkedIterScan for Splitted<T,&str>where T:IterScan{type Output=Vec<<T as IterScan>::Output>;fn mscan<'a,I:Iterator<Item=&'a str>>(self,iter:&mut I)->Option<Self::Output>{let mut iter=iter.next()?.split(self.pat);Some(from_fn(||<T as IterScan>::scan(&mut iter)).collect())}}impl<T,F>MarkedIterScan for F where F:Fn(&str)->Option<T>{type Output=T;fn mscan<'a,I:Iterator<Item=&'a str>>(self,iter:&mut I)->Option<Self::Output>{self(iter.next()?)}}}
pub use self::union_find::UnionFind;
mod union_find{use std::collections::HashMap;#[derive(Clone,Debug)]pub struct UnionFind{parents:Vec<isize>}impl UnionFind{pub fn new(n:usize)->Self{let parents=vec![-1;n];Self{parents}}pub fn find(&mut self,x:usize)->usize{if self.parents[x]<0{x}else{let xx=self.parents[x]as usize;let y=self.find(xx);self.parents[x]=y as isize;y}}pub fn unite(&mut self,x:usize,y:usize)->bool{use std::mem::swap;let mut x=self.find(x);let mut y=self.find(y);if x==y{return false;}if self.parents[x]>self.parents[y]{swap(&mut x,&mut y);}self.parents[x]+=self.parents[y];self.parents[y]=x as isize;true}pub fn size(&mut self,x:usize)->usize{let x=self.find(x);(-self.parents[x])as usize}pub fn same(&mut self,x:usize,y:usize)->bool{self.find(x)==self.find(y)}pub fn members(&mut self,x:usize)->Vec<usize>{let root=self.find(x);(0..self.parents.len()).filter(|i|self.find(*i)==root).collect::<Vec<usize>>()}pub fn roots(&mut self)->Vec<usize>{(0..self.parents.len()).filter(|i|self.parents[*i]<0).collect::<Vec<usize>>()}pub fn all_group_members(&mut self)->HashMap<usize,Vec<usize>>{let mut groups_map=HashMap::new();for x in 0..self.parents.len(){let r=self.find(x);groups_map.entry(r).or_insert_with(||Vec::with_capacity(self.size(r))).push(x);}groups_map}}}
pub use self::range_map::{RangeMap,RangeSet};
mod range_map{use std::{collections::{btree_map,BTreeMap},iter::{Extend,FromIterator}};#[doc=" A map to control intervals that have same values."]#[derive(Debug,Clone)]pub struct RangeMap<K,V>{map:BTreeMap<(K,K),V>}impl<K,V>Default for RangeMap<K,V>where K:Ord{fn default()->Self{Self{map:Default::default()}}}impl<K,V>RangeMap<K,V>{#[doc=" Makes a new, empty `RangeMap`."]pub fn new()->Self where K:Ord{Default::default()}#[doc=" Clears the map, removing all elements."]pub fn clear(&mut self)where K:Ord{self.map.clear();}#[doc=" Returns true if the map contains a value for the key."]pub fn contains_key(&self,key:&K)->bool where K:Clone+Ord{self.get(key).is_some()}#[doc=" Returns a reference to the value corresponding to the key."]pub fn get(&self,key:&K)->Option<&V>where K:Clone+Ord{self.get_range_value(key).map(|(_,v)|v)}#[doc=" Returns the range-value pair corresponding to the key."]pub fn get_range_value(&self,key:&K)->Option<(&(K,K),&V)>where K:Clone+Ord{self.get_right_if(key,|r,_|key==&r.0).or_else(||self.get_left_if(key,|r,_|key<&r.1))}#[doc=" Inserts values into the specified range."]pub fn insert(&mut self,range:(K,K),value:V)where K:Clone+Ord,V:Clone+Eq{self.insert_with(range,value,|_,_|{});}#[doc=" Insert values and operate old range-value pairs."]pub fn insert_with<F>(&mut self,range:(K,K),value:V,mut f:F)where K:Clone+Ord,V:Clone+Eq,F:FnMut((K,K),V){if range.0>=range.1{return;}let mut ins_range=range.clone();if let Some((r,v))=self.pop_left_if(&range.0,|r,v|{range.0<r.1||range.0==r.1&&&value==v}){if range.1<r.1{if value==v{ins_range=r;}else{self.map.insert((r.0,range.0.clone()),v.clone());self.map.insert((range.1.clone(),r.1),v.clone());}f(range.clone(),v);}else{if value==v{ins_range.0=r.0;}else{self.map.insert((r.0,range.0.clone()),v.clone());}if range.0<r.1{f((range.0.clone(),r.1),v);}}}let mut wait=None;if let Some((r,_))=self.pop_right_if(&range.1,|r,v|range.1==r.0&&&value==v){ins_range.1=r.1;}else if let Some((r,v))=self.pop_left_if(&range.1,|r,_|range.1<r.1){if value==v{ins_range.1=r.1;}else{self.map.insert((range.1.clone(),r.1),v.clone());}wait=Some(((r.0,range.1.clone()),v));}let mut f=self.drain_with_inner(range,f);if let Some((r,v))=wait{f(r,v);}self.map.insert(ins_range,value);}#[doc=" Remove values contained in the range."]pub fn remove(&mut self,range:(K,K))where K:Clone+Ord,V:Clone{self.drain_with(range,|_,_|{});}#[doc=" Get a left neighboring range of `[key, key)` if the predicate is satisfied."]pub fn get_left_if<F>(&self,key:&K,mut pred:F)->Option<(&(K,K),&V)>where K:Clone+Ord,F:FnMut(&(K,K),&V)->bool{self.map.range(..(key.clone(),key.clone())).next_back().filter(|(r,v)|pred(r,v))}#[doc=" Get a right neighboring range of `[key, key)` if the predicate is satisfied."]pub fn get_right_if<F>(&self,key:&K,mut pred:F)->Option<(&(K,K),&V)>where K:Clone+Ord,F:FnMut(&(K,K),&V)->bool{self.map.range((key.clone(),key.clone())..).next().filter(|(r,v)|pred(r,v))}#[doc=" Pop a left neighboring range of `[key, key)` if the predicate is satisfied."]pub fn pop_left_if<F>(&mut self,key:&K,pred:F)->Option<((K,K),V)>where K:Clone+Ord,F:FnMut(&(K,K),&V)->bool{match self.get_left_if(key,pred){Some((r,_))=>{let r=r.clone();let v=self.map.remove(&r).unwrap();Some((r,v))}None=>None,}}#[doc=" Pop a right neighboring range of `[key, key)` if the predicate is satisfied."]pub fn pop_right_if<F>(&mut self,key:&K,pred:F)->Option<((K,K),V)>where K:Clone+Ord,F:FnMut(&(K,K),&V)->bool{match self.get_right_if(key,pred){Some((r,_))=>{let r=r.clone();let v=self.map.remove(&r).unwrap();Some((r,v))}None=>None,}}#[doc=" Operate and consume range-value pairs in range when no overlapping."]fn drain_with_inner<F>(&mut self,range:(K,K),mut f:F)->F where K:Clone+Ord,F:FnMut((K,K),V){while let Some((r,_))=self.map.range((range.0.clone(),range.0.clone())..(range.1.clone(),range.1.clone())).next(){let r=r.clone();let v=self.map.remove(&r).unwrap();f(r,v);}f}#[doc=" Operate and consume range-value pairs in range."]pub fn drain_with<F>(&mut self,range:(K,K),mut f:F)where K:Clone+Ord,V:Clone,F:FnMut((K,K),V){if let Some((r,v))=self.pop_left_if(&range.0,|r,_|range.0<r.1){if range.1<r.1{f(range.clone(),v.clone());self.map.insert((range.1.clone(),r.1),v.clone());}else{f((range.0.clone(),r.1),v.clone());}self.map.insert((r.0,range.0.clone()),v);}let mut wait=None;if let Some((r,v))=self.pop_left_if(&range.1,|r,_|range.1<r.1){wait=Some(((r.0,range.1.clone()),v.clone()));self.map.insert((range.1.clone(),r.1),v);}let mut f=self.drain_with_inner(range,f);if let Some((r,v))=wait{f(r,v);}}pub fn iter(&self)->btree_map::Iter<'_,(K,K),V>{self.map.iter()}pub fn iter_mut(&mut self)->btree_map::IterMut<'_,(K,K),V>{self.map.iter_mut()}pub fn keys(&self)->btree_map::Keys<'_,(K,K),V>{self.map.keys()}pub fn values(&self)->btree_map::Values<'_,(K,K),V>{self.map.values()}pub fn values_mut(&mut self)->btree_map::ValuesMut<'_,(K,K),V>{self.map.values_mut()}}impl<K,V>Extend<((K,K),V)>for RangeMap<K,V>where K:Clone+Ord,V:Clone+Eq{fn extend<T:IntoIterator<Item=((K,K),V)>>(&mut self,iter:T){for(range,value)in iter{self.insert(range,value);}}}impl<K,V>FromIterator<((K,K),V)>for RangeMap<K,V>where K:Clone+Ord,V:Clone+Eq{fn from_iter<T:IntoIterator<Item=((K,K),V)>>(iter:T)->Self{let mut map=Self::new();map.extend(iter);map}}#[doc=" A set to control intervals."]#[derive(Debug,Clone)]pub struct RangeSet<T>{map:RangeMap<T,()>}impl<T>Default for RangeSet<T>where T:Ord{fn default()->Self{Self{map:Default::default()}}}impl<T>RangeSet<T>{#[doc=" Makes a new, empty `RangeSet`."]pub fn new()->Self where T:Ord{Default::default()}#[doc=" Clears the set, removing all elements."]pub fn clear(&mut self)where T:Ord{self.map.clear();}#[doc=" Returns true if the set contains a key."]pub fn contains(&self,key:&T)->bool where T:Clone+Ord{self.get_range(key).is_some()}#[doc=" Returns the range corresponding to the key."]pub fn get_range(&self,key:&T)->Option<&(T,T)>where T:Clone+Ord{self.map.get_range_value(key).map(|(r,_)|r)}#[doc=" Inserts into the specified range."]pub fn insert(&mut self,range:(T,T))where T:Clone+Ord{self.insert_with(range,|_|{});}#[doc=" Insert and operate old range."]pub fn insert_with<F>(&mut self,range:(T,T),mut f:F)where T:Clone+Ord,F:FnMut((T,T)){self.map.insert_with(range,(),|r,_|f(r))}#[doc=" Remove items contained in the range."]pub fn remove(&mut self,range:(T,T))where T:Clone+Ord{self.drain_with(range,|_|{});}#[doc=" Get a left neighboring range of `[key, key)` if the predicate is satisfied."]pub fn get_left_if<F>(&self,key:&T,mut pred:F)->Option<&(T,T)>where T:Clone+Ord,F:FnMut(&(T,T))->bool{self.map.get_left_if(key,|r,_|pred(r)).map(|(r,_)|r)}#[doc=" Get a right neighboring range of `[key, key)` if the predicate is satisfied."]pub fn get_right_if<F>(&self,key:&T,mut pred:F)->Option<&(T,T)>where T:Clone+Ord,F:FnMut(&(T,T))->bool{self.map.get_right_if(key,|r,_|pred(r)).map(|(r,_)|r)}#[doc=" Pop a left neighboring range of `[key, key)` if the predicate is satisfied."]pub fn pop_left_if<F>(&mut self,key:&T,mut pred:F)->Option<(T,T)>where T:Clone+Ord,F:FnMut(&(T,T))->bool{self.map.pop_left_if(key,|r,_|pred(r)).map(|(r,_)|r)}#[doc=" Pop a right neighboring range of `[key, key)` if the predicate is satisfied."]pub fn pop_right_if<F>(&mut self,key:&T,mut pred:F)->Option<(T,T)>where T:Clone+Ord,F:FnMut(&(T,T))->bool{self.map.pop_right_if(key,|r,_|pred(r)).map(|(r,_)|r)}#[doc=" Operate and consume in range."]pub fn drain_with<F>(&mut self,range:(T,T),mut f:F)where T:Clone+Ord,F:FnMut((T,T)){self.map.drain_with(range,|r,_|f(r));}pub fn iter(&self)->btree_map::Keys<'_,(T,T),()>{self.map.keys()}}impl<K>Extend<(K,K)>for RangeSet<K>where K:Clone+Ord{fn extend<T:IntoIterator<Item=(K,K)>>(&mut self,iter:T){for range in iter{self.insert(range);}}}impl<K>FromIterator<(K,K)>for RangeSet<K>where K:Clone+Ord{fn from_iter<T:IntoIterator<Item=(K,K)>>(iter:T)->Self{let mut map=Self::new();map.extend(iter);map}}}
0