結果

問題 No.3834 Random K Choose On Tree
コンテスト
ユーザー Solalyth
提出日時 2026-11-28 00:05:23
言語 Rust
(1.99.1 + proconio + num + itertools + ACL)
コンパイル:
/usr/bin/rustc_custom
実行:
./target/release/main
結果
AC  
実行時間 137 ms / 2,000 ms
+ 83µs
コード長 39,980 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 5,003 ms
コンパイル使用メモリ 221,112 KB
実行使用メモリ 60,868 KB
最終ジャッジ日時 2026-11-28 00:05:36
合計ジャッジ時間 13,171 ms
ジャッジサーバーID
(参考情報)
judge1_0 / judge3_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 57
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#![allow(unused_must_use, non_snake_case, unused_labels, unused_imports, unused_assignments)]
use external::*;
use cplib::prelude::*;
use nest as vec;
const INTERACTIVE: bool = false;
// const INTERACTIVE: bool = true; use input_interactive as input;
use mod998::fps;
#[allow(unused)] type Mint = fps::Fp;
#[allow(unused)] macro_rules! fp { ($x:expr) => { Mint::new($x) }; }

fn solve() {
    input! {
        N: usize, K: usize, AB: [(usize1, usize1); N-1]
    }
    
    if N == 1 {
        out << 1; return;
    }
    
    let mut T = graph::tree::Tree::new(0, AB);
    T.calc_et();
    
    let mut F = vec![fp!(0); K+1];
    for i in 0..=K {
        if K/2 < i { F[i] = fp!(O.C(K, i)); }
    }
    let mut G = vec![fp!(0); N-K+1];
    for i in 0..=N-K {
        G[i] = fp!(O.C(N-K, i));
    }
    F = fps::mul(F, &G, !0);
    
    let mut ans = fp!(N);
    for i in 0..N {
        let mut sa = N-1;
        for &j in &T[i] {
            let s = T.size(j); sa -= s;
            ans -= F[s] / O.C(N, s);
        }
        if sa != 0 {
            let s = sa;
            ans -= F[s] / O.C(N, s);
        }
    }
    
    out << ans.val();
}



fn main() {
    out::init(INTERACTIVE || LOCAL);
    let _T = 1;
    // input! { _T: usize }
    // out << _T << end;
    for _ in 0.._T { solve(); }
    out::print();
}

mod external { pub use { proconio::{ input, input_interactive, marker::{Chars as chars, Usize1 as usize1} }, itertools::{Itertools, iproduct}, num::integer::{gcd, lcm, Roots}, num::{Rational64, BigInt, BigRational}, ac_library, }; }

// my library: https://github.com/solalyth/cplib-rs
mod cplib { #![allow(unused_macros, dead_code)] pub const LOCAL: bool = false; pub mod prelude { pub use std::{ collections::{VecDeque, HashMap, HashSet, BTreeMap, BTreeSet, BinaryHeap}, cmp::{Ordering, Reverse}, mem::{replace, take}, iter::repeat_n, }; pub use crate::cplib::{ *, LOCAL, ds::{segtree::*, csr::Edge}, math::modtable::O, algo::func::*, traits::prelude::*, util::output::{out, end}, }; } pub mod ds { pub mod unionfind { pub trait Abelian { type T: Clone + Eq; fn e() -> Self::T; fn add(l: &Self::T, r: &Self::T) -> Self::T; fn inv(x: &Self::T) -> Self::T; fn sub(l: &Self::T, r: &Self::T) -> Self::T { Self::add(l, &Self::inv(r)) } } pub struct Xor; impl Abelian for Xor { type T = bool; fn e() -> bool { false } fn add(l: &bool, r: &bool) -> bool { l^r } fn inv(x: &bool) -> bool { *x } } pub struct UnionFind<Op: Abelian> { par: Vec<usize>, size: Vec<usize>, diff: Vec<Op::T>, } impl UnionFind<Xor> { pub fn new_xor(len: usize) -> Self { Self::new(len) } } impl<Op: Abelian> UnionFind<Op> { pub fn new(len: usize) -> Self { UnionFind { par: (0..len).collect(), size: vec![1; len], diff: vec![Op::e(); len] } } pub fn clear(&mut self) { for i in 0..self.len() { self.par[i] = i; self.size[i] = 1; self.diff[i] = Op::e(); } } pub fn len(&self) -> usize { self.par.len() } pub fn leader(&mut self, i: usize) -> usize { loop { let p = self.par[i]; let g = self.par[p]; if p == g { return g; } self.diff[i] = Op::add(&self.diff[i], &self.diff[p]); self.par[i] = g; } } pub fn size(&mut self, mut i: usize) -> usize { i = self.leader(i); self.size[i] } pub fn is_same(&mut self, i: usize, j: usize) -> bool { self.leader(i) == self.leader(j) } pub fn diff(&mut self, i: usize, j: usize) -> Op::T { assert!(self.is_same(i, j)); Op::sub(&self.diff[i], &self.diff[j]) } pub fn merge(&mut self, i: usize, j: usize, mut w: Op::T) -> (usize, usize) { let (mut old, mut new) = (self.leader(i), self.leader(j)); w = Op::sub(&Op::add(&w, &self.diff[j]), &self.diff[i]); if old == new { return if w == Op::e() { (old, !0) } else { (!0, !0) } } if !(self.size[old] <= self.size[new]) { (old, new) = (new, old); w = Op::inv(&w); } self.par[old] = new; self.diff[old] = w; self.size[new] += self.size[old]; (new, old) } pub fn groups(&mut self) -> Vec<Vec<usize>> { let mut res = vec![vec![]; self.len()]; for i in 0..self.len() { res[self.leader(i)].push(i); } res } pub fn leaders(&self) -> Vec<usize> { (0..self.len()).filter(|&i| self.par[i] == i).collect() } } impl<Op: Abelian> Clone for UnionFind<Op> { fn clone(&self) -> Self { Self { par: self.par.clone(), size: self.size.clone(), diff: self.diff.clone() } } } use std::fmt::*; impl<Op: Abelian> Debug for UnionFind<Op> where Op::T: Debug { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let mut s = String::new(); for g in self.clone().groups() { if !g.is_empty() { s += &format!("{g:?}, "); } } write!(f, "[ {} ]", &s[..s.len()-2]) } } } pub mod segtree { use std::{fmt::Debug, mem::replace, ops::Index, slice::SliceIndex}; #[allow(unused_variables)] pub trait SegtreeOp: Sized { const BEATS: bool = false; type Value: Clone; type Lazy: Clone; fn id_value() -> Self::Value; fn prod_value(l: &Self::Value, r: &Self::Value) -> Self::Value; fn id_lazy() -> Self::Lazy { unsafe{std::mem::zeroed()} } fn prod_lazy(lazy: &mut Self::Lazy, ad: &Self::Lazy) {} fn act(value: &mut Self::Value, lazy: &Self::Lazy) {} fn act_beats(value: &mut Self::Value, lazy: &Self::Lazy) -> bool { panic!() } fn segtree_new(len: usize) -> Segtree<Self> { Segtree::new(len) } fn segtree_iter(iter: impl IntoIterator<IntoIter = impl ExactSizeIterator<Item = Self::Value>>) -> Segtree<Self> { let iter = iter.into_iter(); let mut seg = Segtree::new(iter.len()); let len = seg.len(); for (i, e) in iter.enumerate() { seg.tree[len+i] = e; } seg.update_all(); seg } } pub struct Segtree<Op: SegtreeOp> { pub tree: Vec<Op::Value>, pub lazy: Vec<Op::Lazy>, dep: u32 } impl<Op: SegtreeOp> Segtree<Op> { pub fn new(len: usize) -> Self { let dep = (len.max(2)-1).ilog2() + 2; Segtree { tree: vec![Op::id_value(); 1<<dep], lazy: vec![Op::id_lazy(); 1<<dep], dep } } pub fn len(&self) -> usize { 1 << self.dep-1 } pub fn get(&mut self, mut i: usize) -> &Op::Value { i += self.len(); self.push_line(i); &self.tree[i] } pub fn set(&mut self, mut i: usize, x: Op::Value) where Op::Value: PartialEq { i += self.len(); self.push_line(i); if self.tree[i] == x { return; } self.tree[i] = x; self.update_line(i); } pub fn set_with<T>(&mut self, mut i: usize, f: impl FnOnce(&mut Op::Value) -> T) -> T { i += self.len(); self.push_line(i); let res = f(&mut self.tree[i]); self.update_line(i); res } pub fn fold(&mut self, mut l: usize, mut r: usize) -> Op::Value { l += self.len(); r = (r+self.len()).min(self.len()*2); if l >= r { return Op::id_value(); } let (mut vl, mut vr) = (Op::id_value(), Op::id_value()); self.push_line(l); self.push_line(r-1); while l < r { if l&1 == 1 { vl = Op::prod_value(&vl, &self.tree[l]); l += 1; } if r&1 == 1 { vr = Op::prod_value(&self.tree[r-1], &vr); } l >>= 1; r >>= 1; } Op::prod_value(&vl, &vr) } pub fn apply(&mut self, mut l: usize, mut r: usize, lazy: Op::Lazy) { l += self.len(); r = (r+self.len()).min(self.len()*2); if l >= r { return; } self.push_line(l); self.push_line(r-1); let (mut s, mut t) = (l, r); while s < t { if s&1 == 1 { self.node_apply(s, &lazy); s += 1; } if t&1 == 1 { t -= 1; self.node_apply(t, &lazy); } s >>= 1; t >>= 1; } for i in 1..self.dep { if (l >> i) << i != l { self.update(l >> i); } if (r >> i) << i != r { self.update(r-1 >> i); } } } pub fn max_right(&mut self, l: usize, mut r_max: usize, f: impl Fn(&Op::Value) -> bool) -> usize { assert!(l <= self.len()); r_max = r_max.min(self.len()); if l == self.len() { return r_max; } let (mut r, mut val) = (l + self.len(), Op::id_value()); self.push_line(r); loop { while r&1 == 0 { r >>= 1; } let tmp = Op::prod_value(&val, &self.tree[r]); if !f(&tmp) { while r < self.len() { self.push(r); r *= 2; let tmp = Op::prod_value(&val, &self.tree[r]); if f(&tmp) { val = tmp; r += 1; } } return (r - self.len()).min(r_max); } val = tmp; r += 1; if r & r-1 == 0 { return r_max; } } } pub fn min_left(&mut self, r: usize, f: impl Fn(&Op::Value) -> bool) -> usize { assert!(r <= self.len()); if r == 0 { return 0; } let (mut l, mut val) = (r + self.len(), Op::id_value()); self.push_line(l-1); loop { l -= 1; while l != 1 && l&1 == 1 { l >>= 1; } let tmp = Op::prod_value(&self.tree[l], &val); if !f(&tmp) { while l < self.len() { self.push(l); l = 2*l + 1; let tmp = Op::prod_value(&self.tree[l], &val); if f(&tmp) { val = tmp; l -= 1; } } return l+1 - self.len(); } val = tmp; if l & l-1 == 0 { return 0; } } } fn node_apply(&mut self, i: usize, lazy: &Op::Lazy) { Op::prod_lazy(&mut self.lazy[i], lazy); if !Op::BEATS { Op::act(&mut self.tree[i], lazy); } else if !Op::act_beats(&mut self.tree[i], lazy) { self.push(i); self.update(i); } } fn push(&mut self, i: usize) { if std::mem::size_of::<Op::Lazy>() == 0 { return; } let lazy = replace(&mut self.lazy[i], Op::id_lazy()); self.node_apply(2*i, &lazy); self.node_apply(2*i+1, &lazy); } pub fn push_all(&mut self) { for i in 1..self.len() { self.push(i); } } fn push_line(&mut self, i: usize) { for j in (1..self.dep).rev() { self.push(i>>j); } } fn update(&mut self, i: usize) { self.tree[i] = Op::prod_value(&self.tree[2*i], &self.tree[2*i+1]); } pub fn update_all(&mut self) { for i in (1..self.len()).rev() { self.update(i); } } fn update_line(&mut self, i: usize) { for j in 1..self.dep { self.update(i>>j); } } } impl<Op: SegtreeOp> Clone for Segtree<Op> { fn clone(&self) -> Self { Self { tree: self.tree.clone(), lazy: self.lazy.clone(), dep: self.dep.clone() } } } impl<Op: SegtreeOp> Debug for Segtree<Op> where Op::Value: Debug { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut seg = self.clone(); seg.push_all(); write!(f, "{:?}", &seg.tree[self.len()..]) } } impl<Op: SegtreeOp, I: SliceIndex<[Op::Value]>> Index<I> for Segtree<Op> { type Output = I::Output; fn index(&self, index: I) -> &Self::Output { Index::index(&self.tree[self.len()..], index) } } } pub mod csr { use std::{fmt::Debug, ops::{Index, IndexMut}}; #[derive(Clone, Default)] pub struct CSR<T> { pub(crate) dat: Vec<T>, pub(crate) idx: Vec<usize>, } pub type Edge = CSR<usize>; impl Edge { pub fn from_edges(n: usize, und: bool, rev: bool, uv: &[(usize, usize)]) -> Self { if rev { Self::from_edges_iter(n, und, uv.iter().map(|e| (e.1, e.0))) } else { Self::from_edges_iter(n, und, uv.iter().cloned()) } } pub fn from_edges_iter(n: usize, und: bool, iter: impl IntoIterator<Item = (usize, usize)> + Clone) -> Self { let mut idx = vec![0; n+2]; for (i, j) in iter.clone() { idx[i+2] += 1; if und { idx[j+2] += 1; } } for i in 0..=n { idx[i+1] += idx[i]; } let mut dat = vec![0; idx.pop().unwrap()]; for (i, j) in iter { dat[idx[i+1]] = j; idx[i+1] += 1; if und && i != j { dat[idx[j+1]] = i; idx[j+1] += 1; } } Self { dat, idx } } } impl<T> CSR<T> { pub fn new() -> Self { Self { dat: vec![], idx: vec![0] } } pub fn idx_len(&self) -> usize { self.idx.len()-1 } pub fn dat_len(&self) -> usize { self.dat.len() } pub fn push(&mut self, x: T) { self.dat.push(x); *self.idx.last_mut().unwrap() += 1; } pub fn next_vec(&mut self) { self.idx.push(self.dat.len()); } pub fn internal_push(&mut self, i: usize, v: T) { self.dat[self.idx[i+1]] = v; self.idx[i+1] += 1; } pub fn sort(&mut self) where T: Ord { for i in 0..self.idx_len() { self.dat[self.idx[i]..self.idx[i+1]].sort_unstable(); } } pub fn contains(&self, u: usize, x: &T) -> bool where T: Ord { self[u].binary_search(x).is_ok() } } impl<T> Index<usize> for CSR<T> { type Output = [T]; fn index(&self, i: usize) -> &Self::Output { &self.dat[self.idx[i]..self.idx[i+1]] } } impl<T> IndexMut<usize> for CSR<T> { fn index_mut(&mut self, i: usize) -> &mut Self::Output { &mut self.dat[self.idx[i]..self.idx[i+1]] } } impl<T: Clone + Debug> Debug for CSR<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut s = String::new(); for i in 0..self.idx_len() { s += &format!("{i}: [, "); for x in &self[i] { s.pop(); s.pop(); s += &format!("{x:?}, "); } s.pop(); s.pop(); s += "], "; } s.pop(); s.pop(); write!(f, "{{ {s} }}") } } } } pub mod geo_int { } pub mod algo { pub mod func { pub fn run_length<T: PartialEq>(iter: impl IntoIterator<Item = T>) -> Vec<(T, usize)> { let mut res = vec![]; for t in iter { let Some(l) = res.last_mut() else { res.push((t, 1)); continue; }; if t == l.0 { l.1 += 1; } else { res.push((t, 1)); } } res } #[macro_export] macro_rules! binary_search { ($low:expr, $high:expr) => { if 1<$high.wrapping_sub($low) { Some($high.wrapping_add($low)/2) } else { None } } } } } pub mod graph { pub mod tree { use crate::cplib::ds::csr::Edge; const A: usize = 42; const B: usize = 1<<A; #[derive(Default)] pub struct Tree { pub(crate) n: usize, pub(crate) root: usize, pub(crate) e: Edge, par: Vec<usize>, ord: Vec<usize>, et: Vec<u32>, eti: Vec<u32>, dep: Vec<u32>, st: Vec<u32>, } impl Tree { pub fn new(root: usize, edge: impl IntoIterator<IntoIter = impl ExactSizeIterator<Item = (usize, usize)>>) -> Self { let edge = edge.into_iter(); let n = edge.len()+1; assert!(2 <= n && n < 1<<A/2); let (mut par, mut ord, mut e) = (vec![0; n], vec![], Edge { dat: vec![0; n-1], idx: vec![0; n+2] }); for (u, v) in edge.into_iter() { par[u] += v^B; par[v] += u^B; } assert!((0..n).all(|i| 0 < par[i]>>A)); for i in 0..n { e.idx[i+2] = e.idx[i+1] + (par[i]>>A) - (i != root) as usize; } par[root] = !0; for mut i in 0..n { while par[i]>>A == 1 { let p = par[i] & (B-1); par[i] -= B; par[p] -= i^B; ord.push(i); e.internal_push(p, i); i = p; } } e.idx.pop(); par[root] = !0; ord.push(root); ord.reverse(); Self { n, root, par, ord, e, .. Default::default() } } pub fn par(&self, i: usize) -> usize { debug_assert!(i < self.n); self.par[i] } pub fn order(&self) -> impl '_ + DoubleEndedIterator<Item = usize> { self.ord.iter().cloned() } pub fn order_cp(&self) -> impl '_ + DoubleEndedIterator<Item = (usize, usize)> { self.ord.iter().skip(1).map(|&i| (i, self.par[i])) } pub fn calc_et(&mut self) { if !self.et.is_empty() { return; } let n = self.n; let (mut dfs, mut et, mut eti, mut dep) = (vec![n+self.root, self.root], vec![], vec![0u32; 2*n], vec![0u32; n]); while let Some(i) = dfs.pop() { eti[i] = et.len() as _; et.push(i as _); if i < n { for &j in &self[i] { dep[j] = dep[i]+1; dfs.extend([n+j, j]); } } } let lg = 1+self.n.ilog2() as usize; let mut st = vec![0; 2*n*(lg+1)]; for ei in 0..2*n-1 { let i = et[ei] as usize; st[ei] = if i < n { ei as u32 } else { eti[self.par[i-n]] }; } for b in 0..lg { let (l, r, w) = (b*2*n, (b+1)*2*n, 1<<b); st.copy_within(l..r, r); for i in r..r+2*n-w { st[i] = st[i].min(st[i+w]); } } (self.et, self.eti, self.dep, self.st) = (et, eti, dep, st); } pub fn euler(&self, i: usize) -> usize { self.eti[i] as _ } pub fn euler_out(&self, i: usize) -> usize { self.eti[self.n+i] as _ } pub fn euler_inv(&self, ei: usize) -> usize { self.et[ei] as _ } pub fn euler_ord(&self) -> impl '_ + DoubleEndedIterator<Item = usize> { self.et.iter().map(|&i| i as usize) } pub fn depth(&self, i: usize) -> usize { self.dep[i] as _ } pub fn size(&self, i: usize) -> usize { (self.euler_out(i)-self.euler(i)+1)/2 } pub fn euler_query_down(&self, i: usize, p: usize) -> (usize, usize) { (self.euler(p)+1, self.euler(i)+1) } pub fn euler_query_up(&self, i: usize, p: usize) -> (usize, usize) { (self.euler_out(i), self.euler_out(p)) } pub fn euler_subtree(&self, i: usize) -> (usize, usize) { (self.euler(i), self.euler_out(i)+1) } pub fn lca(&self, mut i: usize, mut j: usize) -> usize { if i == j { return i; } (i, j) = (self.euler(i), self.euler(j)); if i > j { (i, j) = (j, i); } let b = (j-i+1).ilog2() as usize; let w = 2*self.n*b; self.euler_inv(self.st[w+i].min(self.st[w+j+1-(1<<b)]) as _) } } impl std::ops::Index<usize> for Tree { type Output = [usize]; fn index(&self, i: usize) -> &Self::Output { &self.e[i] } } } } pub mod math { pub mod internal { pub mod func { #[macro_export] macro_rules! gcd { ($a:expr, $b:expr) => {{ let (mut a, mut b) = ($a, $b); while b != 0 { (a, b) = (b, a%b); } a }}; ($($x:expr),+) => {{ let mut res = 0; $( res = gcd!(res, $x); )* res }} } #[macro_export] macro_rules! lcm { ($a:expr, $b:expr) => {{ let (a, b) = ($a, $b); if (a, b) == (0, 0) { 0 } else { (a/gcd!(a, b)).saturating_mul(b) } }}; } #[macro_export] macro_rules! extgcd { ($a:expr, $b:expr) => {{ let (a, b) = ($a, $b); let (mut p0, mut q0, mut r0, mut p1, mut q1, mut r1) = (a.signum(), 0, a.abs(), 0, b.signum(), b.abs()); while r1 != 0 { let t = r0/r1; (p0, q0, r0, p1, q1, r1) = (p1, q1, r1, p0 - t*p1, q0 - t*q1, r0 - t*r1); } (p0, q0, r0) }}; } pub fn bezout(mut a: i64, mut b: i64, mut c: i64) -> Option<(i64, i64, i64, i64)> { assert!(b != 0 && a.abs().max(b.abs()) < 3.03e9 as i64); let (x, _, g) = extgcd!(a, b); if c%g != 0 { return None; } (a, b, c) = (a/g, b/g, c/g); let x = (c%b*x).rem_euclid(b); Some((x, (c-a*x)/b, b.abs(), -a*b.signum())) } #[macro_export] macro_rules! modpow { ($x:expr, $n:expr, $m:expr) => {{ let (mut x, mut n, m) = ($x, $n, $m); x %= m; let mut res = 1; while n != 0 { if n & 1 == 1 { res = res * x % m; } x = x * x % m; n /= 2; } res%m }}; } } } pub mod lpf_sieve { const MASK: usize = (1<<16)-1; pub struct LpfSieve { primes: Vec<usize>, table: Vec<usize>, } impl LpfSieve { pub fn new(mut max: usize) -> Self { max = max.max(10); let mut primes = vec![]; let mut table = vec![0; max+1]; for i in 2..=max { let lpf = if table[i] == 0 { primes.push(i); table[i] = (1<<32) + (1<<16); i } else { table[i] & MASK }; for &p in &primes { if !(p <= lpf && i*p <= max) { break; } table[i*p] = if lpf == p { table[i] + (1<<16) | p } else { (i<<32) + (1<<16) + p }; } } Self { primes, table } } fn max(&self) -> usize { self.table.len()-1 } pub fn primes(&self) -> &[usize] { &self.primes } pub fn is_prime(&self, n: usize) -> bool { assert!(n != 0); n != 1 && self.fact(n)[0].0 == n } fn data(&self, n: usize) -> (usize, usize, usize) { if self.table[n] & MASK == 0 { (n, 1, 1) } else { (self.table[n] & MASK, self.table[n]>>16 & MASK, self.table[n]>>32) } } pub fn fold<T>(&self, mut n: usize, mut init: T, mut vpe: impl FnMut(&mut T, usize, usize)) -> T { assert!(n != 0); while n != 1 { let (lpf, exp, nx) = self.data(n); vpe(&mut init, lpf, exp); n = nx; } init } pub fn fact(&self, mut n: usize) -> Vec<(usize, usize)> { assert!(1 <= n && n <= self.max().pow(2)); if n <= self.max() { self.fold(n, vec![], |v, p, e| { v.push((p, e)); }) } else { let mut res = vec![]; for &p in &self.primes { let mut cnt = 0; while n%p == 0 { cnt += 1; n /= p; } if cnt != 0 { res.push((p, cnt)); } if n < p*p { break; } } if n != 1 { res.push((n, 1)); } res } } pub fn divisors(&self, n: usize) -> Vec<usize> { let mut res = vec![1]; for (p, e) in self.fact(n) { for i in 0..res.len() { let mut k = res[i]; for _ in 0..e { k *= p; res.push(k); } } } res } pub fn totient(&self, n: usize) -> Vec<usize> { let mut res = vec![0; n+1]; res[1] = 1; for i in 2..=n { let (lpf, exp, _nx) = self.data(i); res[i] = res[i/lpf] * if exp == 1 { lpf-1 } else { lpf }; } res } pub fn mobius(&self, n: usize) -> Vec<i64> { let mut res = vec![0; n+1]; res[1] = 1; for i in 2..=n { let (_, exp, nx) = self.data(i); if exp == 1 { res[i] = -res[nx]; } } res } } } pub mod modtable { static mut P: usize = 998244353; static mut INV: Vec<usize> = vec![]; static mut F: Vec<usize> = vec![]; static mut FINV: Vec<usize> = vec![]; macro_rules! a { ($n:expr, $x:expr) => {{ O.calc($n); unsafe { let t = $x; debug_assert!(t < P); t } }} } pub const O: _O = _O; pub struct _O; #[allow(non_snake_case, static_mut_refs)] impl _O { pub fn set(&self, p: usize) { unsafe { if p == P { return; } (P, INV, F, FINV) = (p, vec![0, 1], vec![1, 1], vec![1, 1]); } self.calc(100.min(p-1)); } pub fn calc(&self, mut n: usize) { unsafe { if F.len() == 0 { (INV, F, FINV) = (vec![0, 1], vec![1, 1], vec![1, 1]); } let len = F.len(); if n < len { return; } assert!(n < P); n = n.max(len*2)+1; for i in len..n { INV.push(P - (P/i*INV[P%i] % P)); F.push(F[i-1]*i % P); FINV.push(FINV[i-1]*INV[i] % P); } } } pub fn P(&self, n: usize, k: usize) -> usize { if n < k { 0 } else { a!(n, F[n]*FINV[n-k]%P) } } pub fn C(&self, n: usize, k: usize) -> usize { if n < k { 0 } else { a!(n, F[n]*FINV[k]%P*FINV[n-k]%P) } } pub fn M(&self, x: usize, y: usize) -> usize { self.C(x+y, x) } pub fn MC(&self, k: &[usize]) -> usize { let s = k.iter().sum::<usize>(); a!(s, k.iter().fold(F[s], |t, &k| t*FINV[k]%P)) } pub fn color(&self, n: usize, col: usize) -> usize { if n == 0 { 1 } else { O.C(col+n-1, n) } } pub fn grid_line(&self, a: usize, b: usize, k: i64) -> usize { if !(0 <= k && b as i64 <= a as i64 + k) { return 0; } self.C(a+b, a) + unsafe {P} - self.C(a+b, (a as i64 + k + 1) as usize) } pub fn F(&self, n: usize) -> usize { a!(n, F[n]) } pub fn FINV(&self, n: usize) -> usize { a!(n, FINV[n]) } pub fn INV(&self, n: usize) -> usize { a!(n, INV[n]) } pub fn MOD(&self) -> usize { unsafe { P } } } } } pub mod mod998 { pub mod mont { pub const P: u32 = 998244353; const Q: u32 = 998244351; const RR: u64 = 932051910; pub(crate) const fn f(x: u64) -> u32 { red(lzf(x)) } const fn lzf(mut x: u64) -> u32 { x += Q.wrapping_mul(x as _) as u64 * P as u64; (x>>32) as _ } pub(crate) const fn mont(x: u64) -> u32 { f(x*RR) } const fn red(x: u32) -> u32 { if P <= x {x-P} else {x} } pub const fn mul(x: u32, y: u32) -> u32 { f(x as u64 * y as u64) } #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct Fp(pub u32); type MaxInt = i64; static mut INV: Vec<Fp> = vec![]; impl Fp { pub fn new(x: impl TryInto<MaxInt>) -> Fp { Fp(mont(x.try_into().ok().unwrap().rem_euclid(P as _) as _)) } pub const fn raw(val: u32) -> Fp { Fp(mont(val as _)) } pub const fn val(self) -> u32 { f(self.0 as _) } pub const fn inv(self) -> Fp { self.pow((P-2) as _) } pub const fn pow(self, mut n: usize) -> Fp { let (mut x, mut y) = (self.0 as u64, mont(1)); while n != 0 { if n&1 == 1 { y = lzf(x*y as u64); } x = lzf(x*x) as _; n >>= 1; } Fp(red(y)) } pub fn _inv(n: usize) -> Fp { assert!(n != 0); unsafe {INV[n]} } #[allow(static_mut_refs)] pub fn _calc(n: usize) { unsafe { if n <= INV.len() { return; } let mut m = n.max(INV.len()*2); if INV.is_empty() { INV = vec![Fp(0), Fp::raw(1)]; m = m.max(1000); } for i in INV.len()..=m { let t = -INV[P as usize % i] * Fp::raw((P as usize / i) as _); INV.push(t); } } } } use std::{fmt::*, ops::*}; macro_rules! a { ($T:ident, $f:ident, $t:tt) => { impl $T for Fp { fn $f(&mut self, r: Fp) { *self = *self $t r; } } impl<U: TryInto<MaxInt>> $T<U> for Fp { fn $f(&mut self, r: U) { *self = *self $t Fp::new(r); } } }; ($T:ident, $f:ident, $($t:tt)*) => { impl $T for Fp { type Output = Fp; fn $f(self, r: Fp) -> Fp { (($($t)*) as fn(Fp, Fp) -> Fp)(self, r) } } impl<U: TryInto<MaxInt>> $T<U> for Fp { type Output = Fp; fn $f(self, r: U) -> Fp { Fp::$f(self, Fp::new(r)) } } }; } a!(Add, add, |l, r| Fp(red(l.0+r.0))); a!(Sub, sub, |l, r| Fp(red(P+l.0-r.0))); a!(Mul, mul, |l, r| Fp(mul(l.0, r.0))); a!(Div, div, |l, r| l*r.inv()); a!(AddAssign, add_assign, +); a!(SubAssign, sub_assign, -); a!(MulAssign, mul_assign, *); a!(DivAssign, div_assign, /); impl Neg for Fp { type Output = Fp; fn neg(self) -> Fp { Fp(red(P-self.0)) } } impl Display for Fp { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!(f, "{}", self.val()) } } impl Debug for Fp { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!(f, "{}", self.val()) } } #[cfg(test)] mod tests { use rand::{prelude::*, rng}; use super::*; #[test] fn test_fp_by_rand() { let mut rng = rng(); for _ in 0..10000 { let (x, y) = (rng.random_range(0..P), rng.random_range(0..P)); let (mx, my) = (Fp::raw(x), Fp::raw(y)); assert_eq!((mx+my).val(), (x+y)%P); assert_eq!((mx-my).val(), (x+P-y)%P); assert_eq!((mx*my).val() as u64, x as u64 * y as u64 % P as u64); if x != 0 { assert_eq!((mx * mx.inv()).val(), 1); } } } } } pub mod fps { pub use crate::mod998::mont::Fp; const R: [Fp; 22] = [Fp::raw(911660635), Fp::raw(509520358), Fp::raw(369330050), Fp::raw(332049552), Fp::raw(983190778), Fp::raw(123842337), Fp::raw(238493703), Fp::raw(975955924), Fp::raw(603855026), Fp::raw(856644456), Fp::raw(131300601), Fp::raw(842657263), Fp::raw(730768835), Fp::raw(942482514), Fp::raw(806263778), Fp::raw(151565301), Fp::raw(510815449), Fp::raw(503497456), Fp::raw(743006876), Fp::raw(741047443), Fp::raw(56250497), Fp::raw(867605899)]; const IR: [Fp; 22] = [Fp::raw(86583718), Fp::raw(372528824), Fp::raw(373294451), Fp::raw(645684063), Fp::raw(112220581), Fp::raw(692852209), Fp::raw(155456985), Fp::raw(797128860), Fp::raw(90816748), Fp::raw(860285882), Fp::raw(927414960), Fp::raw(354738543), Fp::raw(109331171), Fp::raw(293255632), Fp::raw(535113200), Fp::raw(308540755), Fp::raw(121186627), Fp::raw(608385704), Fp::raw(438932459), Fp::raw(359477183), Fp::raw(824071951), Fp::raw(103369235)]; pub fn pre(mut f: Vec<Fp>, n: usize) -> Vec<Fp> { f.resize(n, Fp(0)); f } pub fn id(n: usize) -> Vec<Fp> { pre(vec![Fp::raw(1)], n) } fn fft(f: &mut [Fp]) { assert!(f.len().is_power_of_two()); for d in (0..f.len().ilog2()).rev() { let h = 1<<d; let mut r = Fp::raw(1); for (s, ch) in f.chunks_exact_mut(2*h).enumerate() { for i in 0..h { let (u, v) = (ch[i], ch[i+h]*r); (ch[i], ch[i+h]) = (u+v, u-v); } r *= R[s.trailing_ones() as usize]; } } } fn ifft(f: &mut [Fp]) { assert!(f.len().is_power_of_two()); for d in 0..f.len().ilog2() { let h = 1<<d; let mut r = Fp::raw(1); for (s, ch) in f.chunks_exact_mut(2*h).enumerate() { let (lo, hi) = ch.split_at_mut(h); for (x, y) in lo.iter_mut().zip(hi.iter_mut()) { let (u, v) = (*x, *y); (*x, *y) = (u+v, (u-v)*r); } r *= IR[s.trailing_ones() as usize]; } } let inv_n = Fp::raw(f.len() as _).inv(); for x in f { *x *= inv_n; } } pub fn mul(mut f: Vec<Fp>, g: &[Fp], deg: usize) -> Vec<Fp> { assert!(f.len() != 0 && g.len() != 0); let d = f.len()+g.len()-1; let n = d.next_power_of_two(); f = pre(f, n+n); f[n..n+g.len()].copy_from_slice(g); fft(&mut f[..n]); fft(&mut f[n..]); for i in 0..n { f[i] = f[i] * f[n+i]; } ifft(&mut f[..n]); pre(f, d.min(deg).max(1)) } pub fn inv(f: &[Fp], deg: usize) -> Vec<Fp> { assert!(f[0] != Fp(0) && deg != 0); let mut res = pre(vec![f[0].inv()], deg); for d in 1.. { let n = 1<<d; if deg <= n/2 { break; } let (mut p, mut q) = (vec![Fp(0); n], vec![Fp(0); n]); for i in 0..n.min(f.len()) { p[i] = f[i]; } for i in 0..n/2 { q[i] = res[i]; } fft(&mut p); fft(&mut q); for i in 0..n { p[i] *= q[i]; } ifft(&mut p); for i in 0..n/2 { p[i] = Fp(0); } fft(&mut p); for i in 0..n { p[i] *= q[i]; } ifft(&mut p); for i in n/2..n.min(deg) { res[i] = -p[i]; } } res } pub fn differential(mut f: Vec<Fp>) -> Vec<Fp> { assert!(f.len() != 0); for i in 1..f.len() { f[i-1] = f[i] * Fp::raw(i as u32); } *f.last_mut().unwrap() = Fp(0); f } pub fn integral(mut f: Vec<Fp>) -> Vec<Fp> { f.push(Fp(0)); Fp::_calc(f.len()); for i in (1..f.len()).rev() { f[i] = f[i-1] * Fp::_inv(i); } f[0] = Fp(0); f } pub fn log(f: Vec<Fp>, deg: usize) -> Vec<Fp> { assert!(f[0].val() == 1); if deg <= 1 { return vec![Fp(0); deg]; } let g = inv(&f, deg-1); integral(mul(differential(pre(f, deg)), &g, deg-1)) } pub fn exp(f: &[Fp], deg: usize) -> Vec<Fp> { assert!(deg != 0); if f.is_empty() { return id(deg); } assert!(f[0] == Fp(0)); let mut b = vec![Fp::raw(1), *f.get(1).unwrap_or(&Fp(0))]; let mut c = vec![Fp::raw(1)]; let mut z2 = vec![Fp::raw(1); 2]; while b.len() < deg { let m = b.len(); let mut y = b.clone(); y.resize(2*m, Fp(0)); fft(&mut y); let z1 = z2; let mut z = vec![Fp(0); m]; for i in 0..m { z[i] = y[i] * z1[i]; } ifft(&mut z); for i in 0..m/2 { z[i] = Fp(0); } fft(&mut z); for i in 0..m { z[i] = -z[i] * z1[i]; } ifft(&mut z); c.extend_from_slice(&z[m/2..m]); z2 = c.clone(); z2.resize(2*m, Fp(0)); fft(&mut z2); let mut x = f[..f.len().min(m)].to_vec(); x.resize(m, Fp(0)); if !x.is_empty() { for i in 0..x.len() { x[i] *= Fp::raw(i as u32); } x.remove(0); } x.push(Fp(0)); fft(&mut x); for i in 0..m { x[i] *= y[i]; } ifft(&mut x); let b_diff = differential(b.clone()); for i in 0..x.len().min(b_diff.len()) { x[i] -= b_diff[i]; } x.resize(2*m, Fp(0)); for i in (0..m-1).rev() { (x[i], x[m+i]) = (Fp(0), x[i]); } fft(&mut x); for i in 0..2*m { x[i] *= z2[i]; } ifft(&mut x); x.pop(); Fp::_calc(x.len()); x.insert(0, Fp(0)); for i in 1..x.len() { x[i] *= Fp::_inv(i); } for i in m..f.len().min(2*m) { x[i] += f[i]; } x[..m].fill(Fp(0)); fft(&mut x); for i in 0..2*m { x[i] *= y[i]; } ifft(&mut x); b.extend_from_slice(&x[m..2*m]); } b.truncate(deg); b } pub fn exp_slow(f: &[Fp], deg: usize) -> Vec<Fp> { assert!(deg != 0); if f.is_empty() { return id(deg); } assert!(f[0].val() == 0); let mut res = vec![Fp::raw(1)]; while res.len() < deg { let n = (res.len()*2).min(deg); let lg = log(res.clone(), n); let mut p = id(n); for i in 0..n { p[i] -= lg[i]; } for i in 0..n.min(f.len()) { p[i] += f[i]; } res = mul(res, &p, n); } res } pub fn pow(f: &[Fp], k: usize, deg: usize) -> Vec<Fp> { if k == 0 { return id(deg); } let l = (0..f.len()).find(|&i| f[i] != Fp(0)).unwrap_or(1<<32); let lk = l.saturating_mul(k); let mut res = vec![Fp(0); deg]; if lk < deg { let mut g = f[l..].to_vec(); let t = f[l].inv(); for x in &mut g { *x *= t; } g = log(g, deg-lk); let t = Fp::new(k); for x in &mut g { *x *= t; } g = exp(&g, deg-lk); let t = f[l].pow(k as _); for x in &mut g { *x *= t; } for i in 0..deg-lk { res[lk+i] = g[i]; } } res } } } pub mod traits { pub mod prelude { pub use super::{ iter_util::*, int_util::*, char_util::*, grid::*, }; } pub mod iter_util { pub trait IterUtil { type T; fn vec(self) -> Vec<Self::T>; fn count_if(self, f: impl FnMut(Self::T) -> bool) -> usize; } impl<T, U: Iterator<Item = T>> IterUtil for U { type T = T; fn vec(self) -> Vec<Self::T> { self.collect() } fn count_if(self, mut f: impl FnMut(T) -> bool) -> usize { let mut t = 0; for x in self { if f(x) { t += 1; } } t } } } pub mod int_util { pub fn floor<T: IntUtil>(l: T, r: T) -> T { l.floor(r).0 } pub fn floor_rem<T: IntUtil>(l: T, r: T) -> T { l.floor(r).1 } pub fn ceil<T: IntUtil>(l: T, r: T) -> T { l.ceil(r).0 } pub fn ceil_rem<T: IntUtil>(l: T, r: T) -> T { l.ceil(r).1 } pub trait IntUtil: Sized { fn floor(self, rhs: Self) -> (Self, Self); fn ceil(self, rhs: Self) -> (Self, Self); fn width(self) -> usize { unimplemented!() } fn test(self, _: usize) -> bool { unimplemented!() } fn rev(self, _: usize) -> Self { unimplemented!() } fn mask(self, _: usize) -> Self { unimplemented!() } fn dbg(self, _: usize) -> String { unimplemented!() } } macro_rules! int { ($($t:ty),+) => {$( impl IntUtil for $t { fn floor(self, rhs: Self) -> ($t, $t) { assert!(0 < rhs); let (q, r) = (self/rhs, self%rhs); if r < 0 { (q-1, r+rhs) } else { (q, r) } } fn ceil(self, rhs: Self) -> ($t, $t) { assert!(0 < rhs); let (q, r) = (self/rhs, self%rhs); if 0 < r { (q+1, rhs-r) } else { (q, -r) } } } )+}; } int!(i32, i64, i128, isize); macro_rules! uint { ($($t:ty),+) => {$( impl IntUtil for $t { fn floor(self, rhs: Self) -> ($t, $t) { (self/rhs, self%rhs) } fn ceil(self, rhs: Self) -> ($t, $t) { let q = (self+rhs-1)/rhs; (q, q*rhs-self) } fn width(self) -> usize { if self == 0 {0} else {self.ilog2() as usize+1} } fn test(self, n: usize) -> bool { n < <$t>::BITS as usize && self>>n&1 == 1 } fn rev(self, n: usize) -> Self { self.reverse_bits() >> <$t>::BITS as usize-n } fn mask(self, n: usize) -> Self { self & ((1<<n)-1) } fn dbg(self, n: usize) -> String { (0..n).rev().map(|i| ['0', '1'][n as usize>>i]).collect() } } )+}; } uint!(u32, u64, u128, usize); } pub mod char_util { pub trait CharUtil: Clone { const LOWER: [Self; 26]; const UPPER: [Self; 26]; const NUMBER: [Self; 10]; fn us(self) -> usize; #[must_use] fn flip(self) -> Self; } impl CharUtil for char { const LOWER: [char; 26] = { let (mut out, mut i) = (['_'; 26], 0); while i < 26 { out[i] = (i+97) as u8 as char; i += 1; } out }; const UPPER: [char; 26] = { let (mut out, mut i) = (['_'; 26], 0); while i < 26 { out[i] = (i+65) as u8 as char; i += 1; } out }; const NUMBER: [char; 10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; fn us(self) -> usize { if self <= '9' { self as usize - 48 } else { (self as usize & 31) - 1 } } fn flip(self) -> Self { (self as u8 ^ 32) as char } } } pub mod grid { pub trait Grid: Copy + Default { const AROUND: [[i64; 2]; 8] = [[0, -1], [0, 1], [-1, 0], [1, 0], [-1, -1], [-1, 1], [1, -1], [1, 1]]; fn add(self, rhs: [i64; 2]) -> Self; fn add_char(self, c: char, n: i64) -> Self { let mut d = Self::AROUND[match c { 'L' => 0, 'R' => 1, 'U' => 2, 'D' => 3, _ => unreachable!() }]; d[0] *= n; d[1] *= n; self.add(d) } fn around4(self) -> [Self; 4] { let mut res = [Default::default(); 4]; for i in 0..4 { res[i] = self.add(Self::AROUND[i]); } res } fn around8(self) -> [Self; 8] { let mut res = [Default::default(); 8]; for i in 0..8 { res[i] = self.add(Self::AROUND[i]); } res } fn rotate(self, n: usize, m: usize, t: i64) -> Self; } impl Grid for [usize; 2] { fn add(mut self, rhs: [i64; 2]) -> Self { for i in 0..2 { self[i] = self[i].wrapping_add_signed(rhs[i] as isize); } self } fn rotate(self, h: usize, w: usize, t: i64) -> Self { let [i, j] = self; match t.rem_euclid(4) { 0 => [i, j], 1 => [j, h-1-i], 2 => [h-1-i, w-1-j], 3 => [w-1-j, i], _ => unreachable!() } } } impl Grid for [i64; 2] { fn add(mut self, rhs: [i64; 2]) -> Self { for i in 0..2 { self[i] += rhs[i]; } self } fn rotate(self, _: usize, _: usize, _: i64) -> Self { unimplemented!() } } } } pub mod util { pub mod output { #![allow(static_mut_refs, non_camel_case_types)] use std::{mem::replace, ops::{Not, Shl}, fmt::Write}; static mut BUFFER: Buffer = Buffer { buf: String::new(), endp: false, prev: Previous::LineHead }; pub struct Buffer { buf: String, endp: bool, prev: Previous, } impl Buffer { fn print(&mut self) { if replace(&mut self.prev, Previous::LineHead) == Previous::LineHead { self.buf.pop(); } if crate::cplib::LOCAL { eprint!("\x1b[32m"); if self.buf.is_empty() { eprintln!("(empty)"); } else { println!("{}", self.buf); } eprint!("\x1b[0m"); } else { if !self.buf.is_empty() { println!("{}", self.buf); } } self.buf.clear(); } fn space(&mut self, sp: bool) { let prev = replace(&mut self.prev, if sp {Previous::Space} else {Previous::NoSpace}); if (sp || prev == Previous::Space) && prev != Previous::LineHead { self.buf.push(' '); } } } #[derive(Clone, Copy)] pub struct out; pub struct out_usp; pub struct end; #[derive(PartialEq, Eq, Clone, Copy)] enum Previous { Space, NoSpace, LineHead, } impl out { pub fn init(endp: bool) { unsafe { BUFFER.buf.reserve(1<<24); BUFFER.endp = endp; } } pub fn print() { unsafe { BUFFER.print(); } } pub fn ln() { unsafe { BUFFER.buf.push('\n'); BUFFER.prev = Previous::LineHead; } } } impl Not for out { type Output = out_usp; fn not(self) -> Self::Output { out_usp } } macro_rules! impl_outs { ($($t:ty, $f:expr);+) => { $( impl $t { fn push<T: Primitive>(v: &T) { unsafe { BUFFER.space($f); v.fmt(&mut BUFFER.buf); } } } impl<T: Primitive> Shl<T> for $t { type Output = Self; fn shl(self, rhs: T) -> Self::Output { Self::push(&rhs); self } } impl Shl<end> for $t { type Output = Self; fn shl(self, _: end) -> Self::Output { unsafe { if BUFFER.endp { BUFFER.print(); } else { BUFFER.buf += "\n"; BUFFER.prev = Previous::LineHead; } } self } } )+ }; } impl_outs!(out, true; out_usp, false); macro_rules! impl_for_slices { ($($t:ty),+) => { $(impl_for_slices!($t; out, out_usp);)+ }; ($t:ty; $($u:ty),+) => { $( impl<T: Primitive> Shl<$t> for $u { type Output = Self; fn shl(self, rhs: $t) -> Self::Output { for v in rhs { Self::push(v); } self } } )+} } impl_for_slices!(&[T], &Vec<T>); trait Primitive { fn fmt(&self, buf: &mut String); } macro_rules! impl_primitive { ($($t:ty),+) => { $(impl_primitive!(@$t); impl_primitive!(@&$t);)+ }; (@$t:ty) => { impl Primitive for $t { fn fmt(&self, buf: &mut String) { write!(buf, "{self}").ok(); } } } } impl_primitive!(char, u32, u64, u128, usize, i32, i64, i128, f32, f64, &str, String); impl Primitive for bool { fn fmt(&self, buf: &mut String) { *buf += if *self { "Yes" } else { "No" }; } } } pub mod macros { #[macro_export] macro_rules! nest { (@parse [$($l:tt)*] for $p:pat in $($iter:tt)+) => { ($($iter)+).into_iter().map(|$p| $($l)*).collect::<Vec<_>>() }; (@parse [$($l:tt)*] $m:tt $($r:tt)*) => { nest!(@parse [$($l)* $m] $($r)*) }; [void; $n:expr] => { std::vec![std::vec![]; $n] }; [void; $n:expr $(;$m:expr)+] => { std::vec![crate::nest![void$(;$m)+]; $n] }; [$($v:expr),*] => { std::vec![$($v),*] }; [$e:expr; $n:expr] => { std::vec![$e; $n] }; [$e:expr; $n:expr $(;$m:expr)+] => { std::vec![crate::nest![$e $(;$m)+]; $n] }; [$($t:tt)*] => { nest!(@parse [] $($t)*) }; } #[macro_export] macro_rules! min { ($x:expr, $y:expr) => {{ let (x, y) = ($x, $y); if x <= y { x } else { y } }}; ($($vl:expr),+) => { [$($vl),+].into_iter().reduce(|x,y| if x <= y {x} else {y}).unwrap() } } #[macro_export] macro_rules! max { ($x:expr, $y:expr) => {{ let (x, y) = ($x, $y); if x >= y { x } else { y } }}; ($($vl:expr),+) => { [$($vl),+].into_iter().reduce(|x,y| if x >= y {x} else {y}).unwrap() } } #[macro_export] macro_rules! chmin { ($dst:expr, $v:expr) => {{ let v = $v; if v < $dst { $dst = v; true } else { false } }}; ($dst:expr, $($vl:expr),+) => { crate::chmin!($dst, crate::min!($($vl),+)) } } #[macro_export] macro_rules! chmax { ($dst:expr, $v:expr) => {{ let v = $v; if $dst < v { $dst = v; true } else { false } }}; ($dst:expr, $($vl:expr),+) => { crate::chmax!($dst, crate::max!($($vl),+)) } } #[macro_export] macro_rules! range { (@acc($x:expr) & $y:expr) => {{ let (mut x, y) = ($x, $y); chmax!(x.0, y.0); chmin!(x.1, y.1); x }}; (@acc($x:expr) | $y:expr) => {{ let (mut x, y) = ($x, $y); chmin!(x.0, y.0); chmax!(x.1, y.1); x }}; (@acc($($t:tt)*) $u:tt $($v:tt)*) => { range!(@acc($($t)* $u) $($v)*) }; ($($t:tt)*) => { range!(@acc() $($t)*) }; } #[macro_export] macro_rules! swap { ($l:expr, $r:expr) => { ($l, $r) = ($r, $l); }; } #[macro_export] macro_rules! vadd { ($v:expr, -$x:expr) => {{ let x = $x; for e in &mut $v { *e -= x; } }}; ($v:expr, $x:expr) => {{ let x = $x; for e in &mut $v { *e += x; } }} } #[macro_export] macro_rules! o { (@acc($($x:tt)*) += $($y:tt)*) => { let t = $($x)* + $($y)*; $($x)* = t; }; (@acc($($x:tt)*) -= $($y:tt)*) => { let t = $($x)* - $($y)*; $($x)* = t; }; (@acc($($x:tt)*) *= $($y:tt)*) => { let t = $($x)* * $($y)*; $($x)* = t; }; (@acc($($x:tt)*) /= $($y:tt)*) => { let t = $($x)* / $($y)*; $($x)* = t; }; (@acc($($x:tt)*) $t:tt $($y:tt)*) => { o!(@acc($($x)* $t) $($y)*) }; ($($x:tt)*) => { o!(@acc() $($x)*) }; } #[macro_export] macro_rules! mp { (@acc($($x:tt)*) [$k:expr] = $y:expr) => { $($x)*.entry($k).or_insert_with(|| $y) }; (@acc($($x:tt)*) $t:tt $($y:tt)*) => { mp!(@acc($($x)* $t) $($y)*) }; ($($x:tt)*) => { mp!(@acc() $($x)*) } } } pub mod debug { #[macro_export] macro_rules! epr { ($($args:tt)*) => {} } #[macro_export] macro_rules! oj_local { ($oj:expr, $local:expr) => { $oj }; } #[macro_export] macro_rules! table { ($t:expr) => {}; } #[macro_export] macro_rules! print_bits { ($t:expr) => {}; } } pub mod func { static mut ID: usize = 0; pub fn id() -> usize { unsafe { ID += 1; ID-1 } } pub fn id_reset() { unsafe { ID = 0; } } } pub mod global { use std::{cell::UnsafeCell, fmt::Debug, mem::MaybeUninit, ops::Deref}; pub struct Global<T>(UnsafeCell<MaybeUninit<T>>); impl<T> Global<T> { pub const fn uninit() -> Self { Self(UnsafeCell::new(MaybeUninit::uninit())) } pub const fn new(x: T) -> Self { Self(UnsafeCell::new(MaybeUninit::new(x))) } pub fn set_global(&self, value: T) { unsafe { (*self.0.get()).write(value); } } pub fn get_global(&self) -> &T { unsafe { (*self.0.get()).assume_init_ref() } } pub fn get_mut_global(&self) -> &mut T { unsafe { (&mut *self.0.get()).assume_init_mut() } } } impl<T> Deref for Global<T> { type Target = T; fn deref(&self) -> &Self::Target { self.get_global() } } impl<T: Debug> Debug for Global<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self.get_global()) } } unsafe impl<T> Sync for Global<T> {} #[macro_export] macro_rules! gl { ($var:ident: $t:ty = $x:expr) => { static $var: crate::util::global::Global<$t> = crate::util::global::Global::<$t>::new($x); }; ($var:ident: $t:ty) => { static $var: crate::util::global::Global<$t> = crate::util::global::Global::uninit(); }; ($var:ident = $x:expr) => { $var.set_global($x); }; ($var:ident) => { $var.get_mut_global() }; } } } }
0