use std::collections::*; use std::io::Write; type Map = BTreeMap; fn main() { input! { t: usize, ask: [(usize, usize); t], } let ans = if t <= 5 { test2(ask) } else { test1(ask) }; let out = std::io::stdout(); let mut out = std::io::BufWriter::new(out.lock()); for a in ans { writeln!(out, "{}", a).ok(); } } fn test1(ask: Vec<(usize, usize)>) -> Vec { let max = ask.iter().map(|p| p.1).max().unwrap(); let mut leaf = vec![]; for i in 1..=max { leaf.push((i, 0, 0)); } for &(n, k) in ask.iter() { leaf.push((k, 1, n)); } leaf.sort(); let size = leaf.len().next_power_of_two(); let mut e = vec![vec![vec![]; 2]; 2]; e[0][0] = vec![M::one()]; e[1][1] = vec![M::one()]; let e = e; let mut mat = vec![e.clone(); 2 * size]; let mut prod = vec![vec![M::one()]; 2 * size]; for (i, &(k, op, n)) in leaf.iter().enumerate() { if op == 1 { prod[size + i] = vec![-M::from(n), M::one()]; } else { let mut res = vec![vec![vec![]; 2]; 2]; let inv2 = M::new(2).inv(); res[0][0] = vec![-M::from(2 * (k - 1)), M::new(2)]; res[1][0] = vec![-M::from(k as i64 - 2) * inv2, M::one()]; res[0][1] = vec![M::from(k)]; mat[size + i] = res; } } for i in (1..size).rev() { prod[i] = prod[2 * i].multiply(&prod[2 * i + 1]); mat[i] = matmul(&mat[2 * i], &mat[2 * i + 1]); } let (prod, mat) = (prod, mat); let mut eval = vec![vec![]; 2 * size]; eval[1] = vec![vec![M::one()], vec![]]; for i in (1..size).filter(|x| prod[*x].len() > 1) { let mut u = std::mem::take(&mut eval[i]); for u in u.iter_mut() { *u = u.rem(&prod[i]); } eval[2 * i] = u.clone(); let mut next = vec![vec![]; 2]; for (u, mat) in u.iter().zip(mat[2 * i].iter()) { for (next, mat) in next.iter_mut().zip(mat.iter()) { next.add_assign(&u.multiply(mat)); } } eval[2 * i + 1] = next; } let mut memo = Map::new(); for (i, &(k, op, n)) in leaf.iter().enumerate() { if op == 1 { let s = eval[size + i][0].eval(M::from(n)); memo.insert((n, k), s); } } ask.into_iter().map(|(n, k)| memo[&(n, k)]).collect() } fn matmul(a: &[Vec>], b: &[Vec>]) -> Vec>> { let mut c = vec![vec![vec![]; 2]; 2]; for (c, a) in c.iter_mut().zip(a.iter()) { for (a, b) in a.iter().zip(b.iter()) { for (c, b) in c.iter_mut().zip(b.iter()) { c.add_assign(&a.multiply(&b)); } } } c } fn test2(ask: Vec<(usize, usize)>) -> Vec { ask.into_iter().map(|(n, k)| solve_p_rec(n, k)).collect() } // i >= 1 // [f_i, f_{i - 1}] = [f_{i - 1}, f_{i - 2}] [[2n-2i+2, i], [n-i/2+1, 0]] fn solve_p_rec(n: usize, k: usize) -> M { if k >= 998244353 { return M::zero(); } if k == 0 { return M::one(); } let mut d = 0usize; while 1 << (2 * d + 2) <= k { d += 1; } let shift_mat = |mat: &[Vec>], c: M, w: usize| -> Vec>> { mat.iter() .map(|mat| { mat.iter() .map(|mat| shift_of_sampling_points_of_polynomial(mat, c, w)) .collect() }) .collect() }; let sq = M::from(1usize << d); let mut mat = vec![vec![vec![M::zero(); 2]; 2]; 2]; mat[0][0][0] = M::from(2 * n); mat[0][0][1] = mat[0][0][0] - sq * M::new(2); mat[0][1][0] = M::one(); mat[0][1][1] = M::one() + sq; mat[1][0][0] = M::from(n) + M::new(2).inv(); mat[1][0][1] = mat[1][0][0] - sq * M::new(2).inv(); for i in 0..d { let w = 1usize << i; let s = sq.inv(); let mut a = shift_mat(&mat, s * M::from(w), w + 1); let b = shift_mat(&mat, s * (M::from(w) * sq + sq), w); let c = shift_mat(&mat, s * (M::from(w) * sq + sq + M::from(w)), w); for (mat, b) in mat.iter_mut().flatten().zip(b.into_iter().flatten()) { mat.extend(b); } for (a, c) in a.iter_mut().flatten().zip(c.into_iter().flatten()) { a.extend(c); } let mut next = vec![vec![vec![]; 2]; 2]; for (next, mat) in next.iter_mut().zip(mat) { for (mat, a) in mat.into_iter().zip(a.iter()) { for (next, a) in next.iter_mut().zip(a) { next.add_assign(&mat.dot(a)); } } } mat = next; } let q = k >> d; mat = shift_mat(&mat, M::zero(), q); let mut dp = [M::one(), M::zero()]; let it = mat[0][0].iter().zip(mat[0][1].iter()); let it = it.zip(mat[1][0].iter()); let it = it.zip(mat[1][1].iter()); for (((a, b), c), d) in it { dp = [*a * dp[0] + *c * dp[1], *b * dp[0] + *d * dp[1]]; } for i in (q << d)..k { let inv2 = M::new(2).inv(); let a = M::from(2 * n) - M::from(2 * i); let c = M::from(n) - M::from(i - 1) * inv2; let b = M::from(i + 1); let d = M::zero(); dp = [a * dp[0] + c * dp[1], b * dp[0] + d * dp[1]]; } dp[0] } // g = (1 + f)^N // として // (1+f)g' = Nf'g // ig_i + 2(i - 1)g_{i-1} + 1/2*(i-2)g_{i - 2} = N(2g_{i - 1} + g_{i - 2}) fn naive(n: usize, k: usize) -> M { if k >= 998244353 { return M::zero(); } let n = n % 998244353; let inv2 = M::new(2).inv(); let mut dp = (M::one(), M::zero()); for i in 1..=k { let invi = M::from(i).inv(); let a = (M::from(2 * n) - M::from(2 * (i - 1))) * invi; let b = (M::from(n) - M::from(i - 2) * inv2) * invi; dp = (dp.0 * a + dp.1 * b, dp.0); /* let mut v = M::from(n) * (M::new(2) * dp.0 + dp.1); v -= M::from(2 * (i - 1)) * dp.0 + M::from(i - 2) * inv2 * dp.1; v *= M::from(i).inv(); dp = (v, dp.0); */ } dp.0 * M::fact(k) } // f(0), f(1), .., f(N - 1) が分かってる, f はN次未満の多項式 // f(c), f(c+1), .., f(c+M-1) を計算する fn shift_of_sampling_points_of_polynomial(f: &[M], c: M, m: usize) -> Vec { assert!(f.len() > 0 && m > 0); let pc = precalc::Precalc::new(f.len() + m); let mut g = Vec::from(f); let mut d = vec![M::zero(); f.len()]; let mut sign = M::one(); for (i, (f, d)) in g.iter_mut().zip(d.iter_mut()).enumerate() { *f *= pc.ifact(i); *d = sign * pc.ifact(i); sign = -sign; } let mut a = g.multiply(&d); a.truncate(f.len()); a.reverse(); for (i, a) in a.iter_mut().enumerate() { *a *= pc.fact(f.len() - 1 - i); } let mut h = vec![M::zero(); f.len()]; let mut v = M::one(); for (i, h) in h.iter_mut().enumerate() { *h = v * pc.ifact(i); v *= c - M::from(i); } let mut b = a.multiply(&h); b.truncate(f.len()); b.reverse(); for (i, b) in b.iter_mut().enumerate() { *b *= pc.ifact(i); } let e = (0..m).map(|k| pc.ifact(k)).collect::>(); let mut res = b.multiply(&e); res.truncate(m); for (i, res) in res.iter_mut().enumerate() { *res *= pc.fact(i); } res } // ---------- begin input macro ---------- // reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 #[macro_export] macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); input_inner!{iter, $($r)*} }; ($($r:tt)*) => { let s = { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); s }; let mut iter = s.split_whitespace(); input_inner!{iter, $($r)*} }; } #[macro_export] macro_rules! input_inner { ($iter:expr) => {}; ($iter:expr, ) => {}; ($iter:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($iter, $t); input_inner!{$iter $($r)*} }; } #[macro_export] macro_rules! read_value { ($iter:expr, ( $($t:tt),* )) => { ( $(read_value!($iter, $t)),* ) }; ($iter:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($iter, $t)).collect::>() }; ($iter:expr, chars) => { read_value!($iter, String).chars().collect::>() }; ($iter:expr, bytes) => { read_value!($iter, String).bytes().collect::>() }; ($iter:expr, usize1) => { read_value!($iter, usize) - 1 }; ($iter:expr, $t:ty) => { $iter.next().unwrap().parse::<$t>().expect("Parse error") }; } // ---------- end input macro ---------- // ---------- begin ModInt ---------- // モンゴメリ乗算を用いる // ほぼCodeforces用 // 注意 // new_unchecked は値xが 0 <= x < modulo であることを仮定 // ModInt の中身は正規化された値で持ってるので直接読んだり書いたりするとぶっ壊れる // 奇素数のみ mod modint { use std::marker::*; use std::ops::*; pub trait Modulo { fn modulo() -> u32; fn rem() -> u32; fn ini() -> u64; fn reduce(x: u64) -> u32 { debug_assert!(x < (Self::modulo() as u64) << 32); let b = (x as u32 * Self::rem()) as u64; let t = x + b * Self::modulo() as u64; let mut c = (t >> 32) as u32; if c >= Self::modulo() { c -= Self::modulo(); } c as u32 } } #[allow(dead_code)] pub enum Mod1_000_000_007 {} impl Modulo for Mod1_000_000_007 { fn modulo() -> u32 { 1_000_000_007 } fn rem() -> u32 { 2226617417 } fn ini() -> u64 { 582344008 } } #[allow(dead_code)] pub enum Mod998_244_353 {} impl Modulo for Mod998_244_353 { fn modulo() -> u32 { 998_244_353 } fn rem() -> u32 { 998244351 } fn ini() -> u64 { 932051910 } } #[allow(dead_code)] pub fn generate_umekomi_modulo(p: u32) { assert!( p < (1 << 31) && p > 2 && p & 1 == 1 && (2u32..).take_while(|v| v * v <= p).all(|k| p % k != 0) ); let mut t = 1u32; let mut s = !p + 1; let mut n = !0u32 >> 2; while n > 0 { if n & 1 == 1 { t *= s; } s *= s; n >>= 1; } let mut ini = (1u64 << 32) % p as u64; ini = (ini << 32) % p as u64; assert!(t * p == !0); println!("pub enum Mod{} {{}}", p); println!("impl Modulo for Mod{} {{", p); println!(" fn modulo() -> u32 {{"); println!(" {}", p); println!(" }}"); println!(" fn rem() -> u32 {{"); println!(" {}", t); println!(" }}"); println!(" fn ini() -> u64 {{"); println!(" {}", ini); println!(" }}"); println!("}}"); let mut f = vec![]; let mut n = p - 1; for i in 2.. { if i * i > n { break; } if n % i == 0 { f.push(i); while n % i == 0 { n /= i; } } } if n > 1 { f.push(n); } let mut order = 1; let mut n = p - 1; while n % 2 == 0 { n /= 2; order <<= 1; } let z = (2u64..) .find(|z| { f.iter() .all(|f| mod_pow(*z, ((p - 1) / *f) as u64, p as u64) != 1) }) .unwrap(); let zeta = mod_pow(z, ((p - 1) / order) as u64, p as u64); println!("impl transform::NTTFriendly for Mod{} {{", p); println!(" fn order() -> usize {{"); println!(" {}", order); println!(" }}"); println!(" fn zeta() -> u32 {{"); println!(" {}", zeta); println!(" }}"); println!("}}"); } pub struct ModInt(u32, PhantomData); impl Clone for ModInt { fn clone(&self) -> Self { ModInt::build(self.0) } } impl Copy for ModInt {} impl Add for ModInt { type Output = ModInt; fn add(self, rhs: Self) -> Self::Output { let mut d = self.0 + rhs.0; if d >= T::modulo() { d -= T::modulo(); } Self::build(d) } } impl AddAssign for ModInt { fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; } } impl Sub for ModInt { type Output = ModInt; fn sub(self, rhs: Self) -> Self::Output { let mut d = self.0 - rhs.0; if self.0 < rhs.0 { d += T::modulo(); } Self::build(d) } } impl SubAssign for ModInt { fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; } } impl Mul for ModInt { type Output = ModInt; fn mul(self, rhs: Self) -> Self::Output { Self::build(T::reduce(self.0 as u64 * rhs.0 as u64)) } } impl MulAssign for ModInt { fn mul_assign(&mut self, rhs: Self) { *self = *self * rhs; } } impl Neg for ModInt { type Output = ModInt; fn neg(self) -> Self::Output { if self.0 == 0 { Self::zero() } else { Self::build(T::modulo() - self.0) } } } impl std::fmt::Display for ModInt { fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result { write!(f, "{}", self.get()) } } impl std::fmt::Debug for ModInt { fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result { write!(f, "{}", self.get()) } } impl std::str::FromStr for ModInt { type Err = std::num::ParseIntError; fn from_str(s: &str) -> Result { let val = s.parse::()?; Ok(ModInt::new(val)) } } impl From for ModInt { fn from(val: usize) -> ModInt { ModInt::new_unchecked((val % T::modulo() as usize) as u32) } } impl From for ModInt { fn from(val: u64) -> ModInt { ModInt::new_unchecked((val % T::modulo() as u64) as u32) } } impl From for ModInt { fn from(val: i64) -> ModInt { let m = T::modulo() as i64; ModInt::new((val % m + m) as u32) } } #[allow(dead_code)] impl ModInt { fn build(d: u32) -> Self { ModInt(d, PhantomData) } pub fn zero() -> Self { Self::build(0) } pub fn is_zero(&self) -> bool { self.0 == 0 } } #[allow(dead_code)] impl ModInt { pub fn new_unchecked(d: u32) -> Self { Self::build(T::reduce(d as u64 * T::ini())) } pub fn new(d: u32) -> Self { Self::new_unchecked(d % T::modulo()) } pub fn one() -> Self { Self::new_unchecked(1) } pub fn get(&self) -> u32 { T::reduce(self.0 as u64) } pub fn pow(&self, mut n: u64) -> Self { let mut t = Self::one(); let mut s = *self; while n > 0 { if n & 1 == 1 { t *= s; } s *= s; n >>= 1; } t } pub fn inv(&self) -> Self { assert!(!self.is_zero()); self.pow((T::modulo() - 2) as u64) } pub fn fact(n: usize) -> Self { (1..=n).fold(Self::one(), |s, a| s * Self::from(a)) } } pub fn mod_pow(mut r: u64, mut n: u64, m: u64) -> u64 { let mut t = 1 % m; while n > 0 { if n & 1 == 1 { t = t * r % m; } r = r * r % m; n >>= 1; } t } } // ---------- end ModInt ---------- // ---------- begin Precalc ---------- mod precalc { use super::modint::*; #[allow(dead_code)] pub struct Precalc { inv: Vec>, fact: Vec>, ifact: Vec>, } #[allow(dead_code)] impl Precalc { pub fn new(n: usize) -> Precalc { let mut inv = vec![ModInt::one(); n + 1]; let mut fact = vec![ModInt::one(); n + 1]; let mut ifact = vec![ModInt::one(); n + 1]; for i in 2..(n + 1) { fact[i] = fact[i - 1] * ModInt::new_unchecked(i as u32); } ifact[n] = fact[n].inv(); if n > 0 { inv[n] = ifact[n] * fact[n - 1]; } for i in (1..n).rev() { ifact[i] = ifact[i + 1] * ModInt::new_unchecked((i + 1) as u32); inv[i] = ifact[i] * fact[i - 1]; } Precalc { inv: inv, fact: fact, ifact: ifact, } } pub fn inv(&self, n: usize) -> ModInt { assert!(n > 0); self.inv[n] } pub fn fact(&self, n: usize) -> ModInt { self.fact[n] } pub fn ifact(&self, n: usize) -> ModInt { self.ifact[n] } pub fn perm(&self, n: usize, k: usize) -> ModInt { if k > n { return ModInt::zero(); } self.fact[n] * self.ifact[n - k] } pub fn comb(&self, n: usize, k: usize) -> ModInt { if k > n { return ModInt::zero(); } self.fact[n] * self.ifact[k] * self.ifact[n - k] } } } // ---------- end Precalc ---------- use modint::*; pub trait NTTFriendly: modint::Modulo { fn order() -> usize; fn zeta() -> u32; } type M = ModInt; impl NTTFriendly for Mod998_244_353 { fn order() -> usize { 8388608 } fn zeta() -> u32 { 15311432 } } // 列に対する命令をテキトーに詰めあわせ // modint, primitive type の2つあたりで使うことを想定 // +, -, * // zero を要求してないのに仮定してる場所がある // // 何も考えずに書き始めたらいろいろよくわからないことになった // 整理 // 長さが等しいときの加算、減算、dot積はok // 長さが異なるときはどうする? // 0埋めされてるというイメージなので // 加算、減算は素直だがdot積はイマイチ // dot積だけ長さが等しいとしておく? // あるいは0埋めのイメージを消すか use std::ops::*; pub trait Zero: Sized + Add { fn zero() -> Self; } pub fn zero() -> T { T::zero() } impl Zero for ModInt { fn zero() -> Self { Self::zero() } } impl Zero for usize { fn zero() -> Self { 0 } } pub trait ArrayAdd { type Item; fn add(&self, rhs: &[Self::Item]) -> Vec; } impl ArrayAdd for [T] where T: Zero + Copy, { type Item = T; fn add(&self, rhs: &[Self::Item]) -> Vec { let mut c = vec![T::zero(); self.len().max(rhs.len())]; c[..self.len()].copy_from_slice(self); c.add_assign(rhs); c } } pub trait ArrayAddAssign { type Item; fn add_assign(&mut self, rhs: &[Self::Item]); } impl ArrayAddAssign for [T] where T: Add + Copy, { type Item = T; fn add_assign(&mut self, rhs: &[Self::Item]) { assert!(self.len() >= rhs.len()); self.iter_mut().zip(rhs).for_each(|(x, a)| *x = *x + *a); } } impl ArrayAddAssign for Vec where T: Zero + Add + Copy, { type Item = T; fn add_assign(&mut self, rhs: &[Self::Item]) { if self.len() < rhs.len() { self.resize(rhs.len(), T::zero()); } self.as_mut_slice().add_assign(rhs); } } pub trait ArraySub { type Item; fn sub(&self, rhs: &[Self::Item]) -> Vec; } impl ArraySub for [T] where T: Zero + Sub + Copy, { type Item = T; fn sub(&self, rhs: &[Self::Item]) -> Vec { let mut c = vec![T::zero(); self.len().max(rhs.len())]; c[..self.len()].copy_from_slice(self); c.sub_assign(rhs); c } } pub trait ArraySubAssign { type Item; fn sub_assign(&mut self, rhs: &[Self::Item]); } impl ArraySubAssign for [T] where T: Sub + Copy, { type Item = T; fn sub_assign(&mut self, rhs: &[Self::Item]) { assert!(self.len() >= rhs.len()); self.iter_mut().zip(rhs).for_each(|(x, a)| *x = *x - *a); } } impl ArraySubAssign for Vec where T: Zero + Sub + Copy, { type Item = T; fn sub_assign(&mut self, rhs: &[Self::Item]) { if self.len() < rhs.len() { self.resize(rhs.len(), T::zero()); } self.as_mut_slice().sub_assign(rhs); } } pub trait ArrayDot { type Item; fn dot(&self, rhs: &[Self::Item]) -> Vec; } impl ArrayDot for [T] where T: Mul + Copy, { type Item = T; fn dot(&self, rhs: &[Self::Item]) -> Vec { assert!(self.len() == rhs.len()); self.iter().zip(rhs).map(|p| *p.0 * *p.1).collect() } } pub trait ArrayDotAssign { type Item; fn dot_assign(&mut self, rhs: &[Self::Item]); } impl ArrayDotAssign for [T] where T: MulAssign + Copy, { type Item = T; fn dot_assign(&mut self, rhs: &[Self::Item]) { assert!(self.len() == rhs.len()); self.iter_mut().zip(rhs).for_each(|(x, a)| *x *= *a); } } pub trait ArrayMul { type Item; fn mul(&self, rhs: &[Self::Item]) -> Vec; } impl ArrayMul for [T] where T: Zero + Mul + Copy, { type Item = T; fn mul(&self, rhs: &[Self::Item]) -> Vec { if self.is_empty() || rhs.is_empty() { return vec![]; } let mut res = vec![zero(); self.len() + rhs.len() - 1]; for (i, a) in self.iter().enumerate() { for (c, b) in res[i..].iter_mut().zip(rhs) { *c = *c + *a * *b; } } res } } pub trait ArrayNTT { type Item; fn ntt(&mut self); fn intt(&mut self); fn multiply(&self, rhs: &[Self::Item]) -> Vec; } impl ArrayNTT for [ModInt] where T: NTTFriendly, { type Item = ModInt; fn ntt(&mut self) { let f = self; let n = f.len(); assert!(n.count_ones() == 1); assert!(n <= T::order()); let len = n.trailing_zeros() as usize; let mut es = [ModInt::zero(); 30]; let mut ies = [ModInt::zero(); 30]; let mut sum_e = [ModInt::zero(); 30]; let cnt2 = T::order().trailing_zeros() as usize; let mut e = ModInt::new_unchecked(T::zeta()); let mut ie = e.inv(); for i in (2..=cnt2).rev() { es[i - 2] = e; ies[i - 2] = ie; e = e * e; ie = ie * ie; } let mut now = ModInt::one(); for i in 0..(cnt2 - 1) { sum_e[i] = es[i] * now; now *= ies[i]; } for ph in 1..=len { let p = 1 << (len - ph); let mut now = ModInt::one(); for (i, f) in f.chunks_exact_mut(2 * p).enumerate() { let (x, y) = f.split_at_mut(p); for (x, y) in x.iter_mut().zip(y.iter_mut()) { let l = *x; let r = *y * now; *x = l + r; *y = l - r; } now *= sum_e[(!i).trailing_zeros() as usize]; } } } fn intt(&mut self) { let f = self; let n = f.len(); assert!(n.count_ones() == 1); assert!(n <= T::order()); let len = n.trailing_zeros() as usize; let mut es = [ModInt::zero(); 30]; let mut ies = [ModInt::zero(); 30]; let mut sum_ie = [ModInt::zero(); 30]; let cnt2 = T::order().trailing_zeros() as usize; let mut e = ModInt::new_unchecked(T::zeta()); let mut ie = e.inv(); for i in (2..=cnt2).rev() { es[i - 2] = e; ies[i - 2] = ie; e = e * e; ie = ie * ie; } let mut now = ModInt::one(); for i in 0..(cnt2 - 1) { sum_ie[i] = ies[i] * now; now *= es[i]; } for ph in (1..=len).rev() { let p = 1 << (len - ph); let mut inow = ModInt::one(); for (i, f) in f.chunks_exact_mut(2 * p).enumerate() { let (x, y) = f.split_at_mut(p); for (x, y) in x.iter_mut().zip(y.iter_mut()) { let l = *x; let r = *y; *x = l + r; *y = (l - r) * inow; } inow *= sum_ie[(!i).trailing_zeros() as usize]; } } let ik = ModInt::new_unchecked((T::modulo() + 1) >> 1).pow(len as u64); for f in f.iter_mut() { *f *= ik; } } fn multiply(&self, rhs: &[Self::Item]) -> Vec { if self.len().min(rhs.len()) <= 32 { return self.mul(rhs); } let size = (self.len() + rhs.len() - 1).next_power_of_two(); let mut f = vec![ModInt::zero(); size]; let mut g = vec![ModInt::zero(); size]; f[..self.len()].copy_from_slice(self); g[..rhs.len()].copy_from_slice(rhs); f.ntt(); g.ntt(); f.dot_assign(&g); f.intt(); f.truncate(self.len() + rhs.len() - 1); f } } pub trait PolynomialOperation { type Item; fn eval(&self, x: Self::Item) -> Self::Item; fn derivative(&self) -> Vec; fn integral(&self) -> Vec; } impl PolynomialOperation for [ModInt] { type Item = ModInt; fn eval(&self, x: Self::Item) -> Self::Item { self.iter().rev().fold(ModInt::zero(), |s, a| s * x + *a) } fn derivative(&self) -> Vec { if self.len() <= 1 { return vec![]; } self[1..] .iter() .enumerate() .map(|(k, a)| ModInt::new_unchecked(k as u32 + 1) * *a) .collect() } fn integral(&self) -> Vec { if self.is_empty() { return vec![]; } let mut inv = vec![ModInt::one(); self.len() + 1]; let mut mul = ModInt::zero(); for i in 1..=self.len() { mul += ModInt::one(); inv[i] = inv[i - 1] * mul; } let mut prod = inv[self.len()].inv(); for i in (1..=self.len()).rev() { inv[i] = self[i - 1] * inv[i - 1] * prod; prod *= mul; mul -= ModInt::one(); } inv[0] = ModInt::zero(); inv } } pub trait FPSOperation { type Item; fn inverse(&self, n: usize) -> Vec; fn div_rem(&self, rhs: &Self) -> (Vec, Vec); fn rem(&self, rhs: &Self) -> Vec; fn div(&self, rhs: &Self) -> Vec; fn log(&self, n: usize) -> Vec; fn exp(&self, n: usize) -> Vec; } impl FPSOperation for [ModInt] { type Item = ModInt; fn inverse(&self, n: usize) -> Vec { assert!(self.len() > 0 && !self[0].is_zero()); let len = n.next_power_of_two(); assert!(2 * len <= T::order()); let mut b = vec![ModInt::zero(); n]; b[0] = self[0].inv(); let mut f = Vec::with_capacity(2 * len); let mut g = Vec::with_capacity(2 * len); let mut size = 1; while size < n { g.clear(); g.extend(b.iter().take(size)); g.resize(2 * size, ModInt::zero()); f.clear(); f.extend(self.iter().take(2 * size)); f.resize(2 * size, ModInt::zero()); f.ntt(); g.ntt(); f.dot_assign(&g); f.intt(); f[..size].iter_mut().for_each(|f| *f = ModInt::zero()); f.ntt(); f.dot_assign(&g); f.intt(); for (b, g) in b[size..].iter_mut().zip(&f[size..]) { *b = *b - *g; } size *= 2; } b } fn div(&self, rhs: &Self) -> Vec { assert!(!rhs.last().unwrap().is_zero()); let n = self.len(); let m = rhs.len(); assert!(m > 0); if n < m { return vec![]; } if m <= 64 { let mut a = Vec::from(self); let inv = rhs[m - 1].inv(); let mut div = Vec::with_capacity(n - m + 1); for i in ((m - 1)..n).rev() { let p = inv * a[i]; div.push(p); for (a, rhs) in a[..=i].iter_mut().rev().zip(rhs.iter().rev()) { *a -= *rhs * p; } } div.reverse(); return div; } let mut a = Vec::from(self); a.reverse(); a.truncate(n - m + 1); let mut b = Vec::from(rhs); b.reverse(); let ib = b.inverse(n - m + 1); let mut id = a.multiply(&ib); id.truncate(n - m + 1); let mut div = id.clone(); div.reverse(); div } fn div_rem(&self, rhs: &Self) -> (Vec, Vec) { let div = self.div(rhs); let mut rem = self.sub(&rhs.multiply(&div)); rem.truncate(rhs.len() - 1); (div, rem) } fn rem(&self, rhs: &Self) -> Vec { self.div_rem(rhs).1 } fn log(&self, n: usize) -> Vec { assert!(self.get(0).map_or(false, |p| p.get() == 1)); let mut b = self.derivative().multiply(&self.inverse(n)); b.truncate(n - 1); let mut b = b.integral(); b.resize(n, ModInt::zero()); b } fn exp(&self, n: usize) -> Vec { assert!(self.get(0).map_or(true, |a| a.is_zero())); assert!(n <= T::order()); let mut b = vec![ModInt::one()]; let mut size = 1; while size < n { size <<= 1; let f = b.log(size); let g = self[..self.len().min(size)].sub(&f); b = b.multiply(&g).add(&b); b.truncate(size); } b.truncate(n); b.resize(n, ModInt::zero()); b } } // test // yuki907: https://yukicoder.me/submissions/712523 // hhkb2020: https://atcoder.jp/contests/hhkb2020/submissions/26997806 //