fn main() { #![allow(unused_imports, unused_macros)] prepare_io!(_in_buf, scanner, _out); macro_rules ! print { ($ ($ arg : tt) *) => (:: std :: write ! (_out , $ ($ arg) *) . expect ("io error")) } macro_rules ! println { ($ ($ arg : tt) *) => (:: std :: writeln ! (_out , $ ($ arg) *) . expect ("io error")) } scan!(scanner, n, (g, _): {TreeGraphScanner::::new(n)}); let r = ReRooting::<(AdditiveOperation, AdditiveOperation), _>::new(&g, |d, _, o| { (d.0 + d.1, d.1 + o.is_some() as usize) }); let distsum = (0..n).map(|u| r.dp[u].0).sum::(); let ans = M::from(distsum) / (M::from(n - 1) * M::from(n) * M::from(n - 1)); println!("{}", M::one() - ans); } pub type M = mint_basic::MInt998244353; #[macro_export] macro_rules! prepare_io { ($ in_buf : ident , $ scanner : ident , $ out : ident) => { use std::io::{stdout, BufWriter, Write as _}; let $in_buf = read_stdin_all_unchecked(); let mut $scanner = Scanner::new(&$in_buf); let $out = stdout(); let mut $out = BufWriter::new($out.lock()); }; } pub fn echo( mut writer: impl std::io::Write, iter: impl IntoIterator, sep: impl std::fmt::Display, ) -> std::io::Result<()> { let mut iter = iter.into_iter(); if let Some(item) = iter.next() { write!(writer, "{}", item)?; } for item in iter { write!(writer, "{}{}", sep, item)?; } writeln!(writer) } 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_stdin_line() -> String { let mut s = String::new(); std::io::stdin().read_line(&mut s).expect("io error"); s } pub use scanner_impls::{IterScan, MarkedIterScan, Scanner}; mod scanner_impls { pub trait IterScan: Sized { type Output; fn scan<'a, I: Iterator>(iter: &mut I) -> Option; } pub trait MarkedIterScan: Sized { type Output; fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option; } #[derive(Clone, Debug)] pub struct Scanner<'a> { 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(&mut self) -> ::Output where T: IterScan, { ::scan(&mut self.iter).expect("scan error") } #[inline] pub fn mscan(&mut self, marker: T) -> ::Output where T: MarkedIterScan, { marker.mscan(&mut self.iter).expect("scan error") } #[inline] pub fn scan_vec(&mut self, size: usize) -> Vec<::Output> where T: IterScan, { (0..size) .map(|_| ::scan(&mut self.iter).expect("scan error")) .collect() } #[inline] pub fn iter<'b, T>(&'b mut self) -> ScannerIter<'a, 'b, 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 { ($ ($ 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) ?,) *)) } } } ; } iter_scan_tuple_impl!(); iter_scan_tuple_impl!(A); iter_scan_tuple_impl ! (A B); iter_scan_tuple_impl ! (A B C); iter_scan_tuple_impl ! (A B C D); iter_scan_tuple_impl ! (A B C D E); iter_scan_tuple_impl ! (A B C D E F); iter_scan_tuple_impl ! (A B C D E F G); iter_scan_tuple_impl ! (A B C D E F G H); iter_scan_tuple_impl ! (A B C D E F G H I); iter_scan_tuple_impl ! (A B C D E F G H I J); 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 T>, } impl<'a, 'b, T> Iterator for ScannerIter<'a, 'b, T> where T: IterScan, { type Item = ::Output; #[inline] fn next(&mut self) -> Option { ::scan(&mut self.inner.iter) } } } pub use marker_impls::{CharWithBase, Chars, CharsWithBase, Collect, SizedCollect, Usize1}; mod marker_impls { use super::*; use std::{ iter::{repeat_with, FromIterator}, marker::PhantomData, }; #[derive(Debug, Copy, Clone)] pub struct Usize1; impl IterScan for Usize1 { type Output = usize; #[inline] fn scan<'a, I: Iterator>(iter: &mut I) -> Option { ::scan(iter)?.checked_sub(1) } } #[derive(Debug, Copy, Clone)] pub struct CharWithBase(pub char); impl MarkedIterScan for CharWithBase { type Output = usize; #[inline] fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option { Some((::scan(iter)? as u8 - self.0 as u8) as usize) } } #[derive(Debug, Copy, Clone)] pub struct Chars; impl IterScan for Chars { type Output = Vec; #[inline] fn scan<'a, I: Iterator>(iter: &mut I) -> Option { Some(iter.next()?.chars().collect()) } } #[derive(Debug, Copy, Clone)] pub struct CharsWithBase(pub char); impl MarkedIterScan for CharsWithBase { type Output = Vec; #[inline] fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option { Some( iter.next()? .chars() .map(|c| (c as u8 - self.0 as u8) as usize) .collect(), ) } } #[derive(Debug, Copy, Clone)] pub struct Collect::Output>> where T: IterScan, B: FromIterator<::Output>, { size: usize, _marker: PhantomData (T, B)>, } impl Collect where T: IterScan, B: FromIterator<::Output>, { pub fn new(size: usize) -> Self { Self { size, _marker: PhantomData, } } } impl MarkedIterScan for Collect where T: IterScan, B: FromIterator<::Output>, { type Output = B; #[inline] fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option { repeat_with(|| ::scan(iter)) .take(self.size) .collect() } } #[derive(Debug, Copy, Clone)] pub struct SizedCollect::Output>> where T: IterScan, B: FromIterator<::Output>, { _marker: PhantomData (T, B)>, } impl IterScan for SizedCollect where T: IterScan, B: FromIterator<::Output>, { type Output = B; #[inline] fn scan<'a, I: Iterator>(iter: &mut I) -> Option { let size = usize::scan(iter)?; repeat_with(|| ::scan(iter)) .take(size) .collect() } } } #[macro_export] macro_rules ! scan_value { ($ scanner : expr , ($ ($ t : tt) ,*)) => { ($ ($ crate :: scan_value ! ($ scanner , $ t)) ,*) } ; ($ scanner : expr , [$ t : tt ; $ len : expr]) => { (0 ..$ len) . map (| _ | $ crate :: scan_value ! ($ scanner , $ t)) . collect ::< Vec < _ >> () } ; ($ scanner : expr , [$ t : ty ; $ len : expr]) => { $ scanner . scan_vec ::<$ t > ($ len) } ; ($ scanner : expr , [$ t : ty]) => { $ scanner . iter ::<$ t > () } ; ($ scanner : expr , { $ e : expr }) => { $ scanner . mscan ($ e) } ; ($ scanner : expr , $ t : ty) => { $ scanner . scan ::<$ t > () } ; } #[macro_export] macro_rules ! scan { ($ scanner : expr) => { } ; ($ scanner : expr ,) => { } ; ($ scanner : expr , mut $ var : tt : $ t : tt) => { let mut $ var = $ crate :: scan_value ! ($ scanner , $ t) ; } ; ($ scanner : expr , $ var : tt : $ t : tt) => { let $ var = $ crate :: scan_value ! ($ scanner , $ t) ; } ; ($ scanner : expr , mut $ var : tt : $ t : tt , $ ($ rest : tt) *) => { let mut $ var = $ crate :: scan_value ! ($ scanner , $ t) ; scan ! ($ scanner , $ ($ rest) *) } ; ($ scanner : expr , $ var : tt : $ t : tt , $ ($ rest : tt) *) => { let $ var = $ crate :: scan_value ! ($ scanner , $ t) ; scan ! ($ scanner , $ ($ rest) *) } ; ($ scanner : expr , mut $ var : tt) => { let mut $ var = $ crate :: scan_value ! ($ scanner , usize) ; } ; ($ scanner : expr , $ var : tt) => { let $ var = $ crate :: scan_value ! ($ scanner , usize) ; } ; ($ scanner : expr , mut $ var : tt , $ ($ rest : tt) *) => { let mut $ var = $ crate :: scan_value ! ($ scanner , usize) ; scan ! ($ scanner , $ ($ rest) *) } ; ($ scanner : expr , $ var : tt , $ ($ rest : tt) *) => { let $ var = $ crate :: scan_value ! ($ scanner , usize) ; scan ! ($ scanner , $ ($ rest) *) } ; } pub use sparse_graph::{ Adjacency, BidirectionalGraphScanner, BidirectionalSparseGraph, DirectedGraphScanner, DirectedSparseGraph, SparseGraph, TreeGraphScanner, UndirectedGraphScanner, UndirectedSparseGraph, }; pub mod sparse_graph { use super::*; use std::{iter, marker::PhantomData, ops, slice}; type Marker = PhantomData T>; #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct DirectedEdge; #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct UndirectedEdge; #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct BidirectionalEdge; #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Adjacency { pub id: usize, pub to: usize, } impl Adjacency { pub fn new(id: usize, to: usize) -> Adjacency { Adjacency { id, to } } } /// Static Sparse Graph represented as Compressed Sparse Row. #[derive(Debug, Clone)] pub struct SparseGraph { vsize: usize, pub start: Vec, pub elist: Vec, pub edges: Vec<(usize, usize)>, _marker: Marker, } impl SparseGraph { /// Return the number of vertices. pub fn vertices_size(&self) -> usize { self.vsize } /// Return the number of edges. pub fn edges_size(&self) -> usize { self.edges.len() } /// Return an iterator over graph vertices. pub fn vertices(&self) -> ops::Range { 0..self.vertices_size() } /// Return a slice of adjacency vertices. pub fn adjacencies(&self, v: usize) -> slice::Iter<'_, Adjacency> { self.elist[self.start[v]..self.start[v + 1]].iter() } } pub trait SparseGraphConstruction: Sized { fn construct_graph(vsize: usize, edges: Vec<(usize, usize)>) -> SparseGraph; } impl SparseGraph { /// Construct graph from edges. pub fn from_edges(vsize: usize, edges: Vec<(usize, usize)>) -> Self { D::construct_graph(vsize, edges) } } impl SparseGraphConstruction for DirectedEdge { fn construct_graph(vsize: usize, edges: Vec<(usize, usize)>) -> SparseGraph { let mut start: Vec<_> = iter::repeat(0).take(vsize + 1).collect(); let mut elist = Vec::with_capacity(edges.len()); unsafe { elist.set_len(edges.len()) } for (from, _) in edges.iter().cloned() { start[from] += 1; } for i in 1..=vsize { start[i] += start[i - 1]; } for (id, (from, to)) in edges.iter().cloned().enumerate() { start[from] -= 1; elist[start[from]] = Adjacency::new(id, to); } SparseGraph { vsize, start, elist, edges, _marker: PhantomData, } } } impl SparseGraphConstruction for UndirectedEdge { fn construct_graph(vsize: usize, edges: Vec<(usize, usize)>) -> SparseGraph { let mut start: Vec<_> = iter::repeat(0).take(vsize + 1).collect(); let mut elist = Vec::with_capacity(edges.len() * 2); unsafe { elist.set_len(edges.len() * 2) } for (from, to) in edges.iter().cloned() { start[to] += 1; start[from] += 1; } for i in 1..=vsize { start[i] += start[i - 1]; } for (id, (from, to)) in edges.iter().cloned().enumerate() { start[from] -= 1; elist[start[from]] = Adjacency::new(id, to); start[to] -= 1; elist[start[to]] = Adjacency::new(id, from); } SparseGraph { vsize, start, elist, edges, _marker: PhantomData, } } } impl SparseGraphConstruction for BidirectionalEdge { fn construct_graph(vsize: usize, edges: Vec<(usize, usize)>) -> SparseGraph { let mut start: Vec<_> = iter::repeat(0).take(vsize + 1).collect(); let mut elist = Vec::with_capacity(edges.len() * 2); unsafe { elist.set_len(edges.len() * 2) } for (from, to) in edges.iter().cloned() { start[to] += 1; start[from] += 1; } for i in 1..=vsize { start[i] += start[i - 1]; } for (id, (from, to)) in edges.iter().cloned().enumerate() { start[from] -= 1; elist[start[from]] = Adjacency::new(id * 2, to); start[to] -= 1; elist[start[to]] = Adjacency::new(id * 2 + 1, from); } SparseGraph { vsize, start, elist, edges, _marker: PhantomData, } } } pub type DirectedSparseGraph = SparseGraph; pub type UndirectedSparseGraph = SparseGraph; pub type BidirectionalSparseGraph = SparseGraph; pub struct SparseGraphScanner, T: IterScan, D> { vsize: usize, esize: usize, _marker: Marker<(U, T, D)>, } impl, T: IterScan, D> SparseGraphScanner { pub fn new(vsize: usize, esize: usize) -> Self { Self { vsize, esize, _marker: PhantomData, } } } impl, T: IterScan, D: SparseGraphConstruction> MarkedIterScan for SparseGraphScanner { type Output = (SparseGraph, Vec<::Output>); fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option { let mut edges = Vec::with_capacity(self.esize); let mut rest = Vec::with_capacity(self.esize); for _ in 0..self.esize { edges.push((U::scan(iter)?, U::scan(iter)?)); rest.push(T::scan(iter)?); } let graph = SparseGraph::from_edges(self.vsize, edges); Some((graph, rest)) } } pub type DirectedGraphScanner = SparseGraphScanner; pub type UndirectedGraphScanner = SparseGraphScanner; pub type BidirectionalGraphScanner = SparseGraphScanner; pub struct TreeGraphScanner, T: IterScan = ()> { vsize: usize, _marker: Marker<(U, T)>, } impl, T: IterScan> TreeGraphScanner { pub fn new(vsize: usize) -> Self { Self { vsize, _marker: PhantomData, } } } impl, T: IterScan> MarkedIterScan for TreeGraphScanner { type Output = (UndirectedSparseGraph, Vec<::Output>); fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option { UndirectedGraphScanner::::new(self.vsize, self.vsize - 1).mscan(iter) } } } /// dynamic programming on all-rooted trees /// /// caluculate all subtrees (hanging on the edge) in specific ordering, /// each subtree calculated in the order of merge and rooting #[derive(Clone, Debug)] pub struct ReRooting<'a, M: Monoid, F: Fn(&M::T, usize, Option) -> M::T> { graph: &'a UndirectedSparseGraph, /// dp\[v\]: result of v-rooted tree pub dp: Vec, /// ep\[e\]: result of e-subtree, if e >= n then reversed-e-subtree pub ep: Vec, /// rooting(data, vid, (Optional)eid): add root node(vid), result subtree is edge(eid) rooting: F, } impl<'a, M, F> ReRooting<'a, M, F> where M: Monoid, F: Fn(&M::T, usize, Option) -> M::T, { pub fn new(graph: &'a UndirectedSparseGraph, rooting: F) -> Self { let dp = vec![M::unit(); graph.vertices_size()]; let ep = vec![M::unit(); graph.vertices_size() * 2]; let mut self_ = Self { graph, dp, ep, rooting, }; self_.rerooting(); self_ } #[inline] fn eidx(&self, u: usize, a: &Adjacency) -> usize { a.id + self.graph.edges_size() * (u > a.to) as usize } #[inline] fn reidx(&self, u: usize, a: &Adjacency) -> usize { a.id + self.graph.edges_size() * (u < a.to) as usize } #[inline] fn merge(&self, x: &M::T, y: &M::T) -> M::T { M::operate(x, y) } #[inline] fn add_subroot(&self, x: &M::T, vid: usize, eid: usize) -> M::T { (self.rooting)(x, vid, Some(eid)) } #[inline] fn add_root(&self, x: &M::T, vid: usize) -> M::T { (self.rooting)(x, vid, None) } fn dfs(&mut self, pa: &Adjacency, p: usize) { let u = pa.to; let pi = self.eidx(p, pa); for a in self.graph.adjacencies(u).filter(|a| a.to != p) { let i = self.eidx(u, a); self.dfs(a, u); self.ep[pi] = self.merge(&self.ep[pi], &self.ep[i]); } self.ep[pi] = self.add_subroot(&self.ep[pi], u, pa.id); } fn efs(&mut self, u: usize, p: usize) { let m = self.graph.adjacencies(u).len(); let mut left = vec![M::unit(); m + 1]; let mut right = vec![M::unit(); m + 1]; for (k, a) in self.graph.adjacencies(u).enumerate() { let i = self.eidx(u, a); left[k + 1] = self.merge(&left[k], &self.ep[i]); } for (k, a) in self.graph.adjacencies(u).enumerate().rev() { let i = self.eidx(u, a); right[k] = self.merge(&right[k + 1], &self.ep[i]); } self.dp[u] = self.add_root(&left[m], u); for (k, a) in self.graph.adjacencies(u).enumerate() { if a.to != p { let i = self.reidx(u, a); self.ep[i] = self.merge(&left[k], &right[k + 1]); self.ep[i] = self.add_subroot(&self.ep[i], u, a.id); self.efs(a.to, u); } } } fn rerooting(&mut self) { for a in self.graph.adjacencies(0) { self.dfs(a, 0); } self.efs(0, std::usize::MAX); } } /// binary operaion: $T \circ T \to T$ pub trait Magma { /// type of operands: $T$ type T: Clone; /// binary operaion: $\circ$ fn operate(x: &Self::T, y: &Self::T) -> Self::T; #[inline] fn reverse_operate(x: &Self::T, y: &Self::T) -> Self::T { Self::operate(y, x) } #[inline] fn operate_assign(x: &mut Self::T, y: &Self::T) { *x = Self::operate(x, y); } } /// $\forall a,\forall b,\forall c \in T, (a \circ b) \circ c = a \circ (b \circ c)$ pub trait Associative {} /// associative binary operation pub trait SemiGroup: Magma + Associative {} impl SemiGroup for S {} /// $\exists e \in T, \forall a \in T, e \circ a = a \circ e = e$ pub trait Unital: Magma { /// identity element: $e$ fn unit() -> Self::T; #[inline] fn is_unit(x: &Self::T) -> bool where ::T: PartialEq, { x == &Self::unit() } #[inline] fn set_unit(x: &mut Self::T) { *x = Self::unit(); } } /// associative binary operation and an identity element pub trait Monoid: SemiGroup + Unital { /// binary exponentiation: $x^n = x\circ\ddots\circ x$ fn pow(mut x: Self::T, mut n: usize) -> Self::T { let mut res = Self::unit(); while n > 0 { if n & 1 == 1 { res = Self::operate(&res, &x); } x = Self::operate(&x, &x); n >>= 1; } res } } impl Monoid for M {} /// $\exists e \in T, \forall a \in T, \exists b,c \in T, b \circ a = a \circ c = e$ pub trait Invertible: Magma { /// $a$ where $a \circ x = e$ fn inverse(x: &Self::T) -> Self::T; #[inline] fn rinv_operate(x: &Self::T, y: &Self::T) -> Self::T { Self::operate(x, &Self::inverse(y)) } } /// associative binary operation and an identity element and inverse elements pub trait Group: Monoid + Invertible {} impl Group for G {} /// $\forall a,\forall b \in T, a \circ b = b \circ a$ pub trait Commutative {} /// commutative monoid pub trait AbelianMonoid: Monoid + Commutative {} impl AbelianMonoid for M {} /// commutative group pub trait AbelianGroup: Group + Commutative {} impl AbelianGroup for G {} /// $\forall a \in T, a \circ a = a$ pub trait Idempotent {} /// idempotent monoid pub trait IdempotentMonoid: Monoid + Idempotent {} impl IdempotentMonoid for M {} #[macro_export] macro_rules ! monoid_fold { ($ m : ty) => { <$ m as Unital >:: unit () } ; ($ m : ty ,) => { <$ m as Unital >:: unit () } ; ($ m : ty , $ f : expr) => { $ f } ; ($ m : ty , $ f : expr , $ ($ ff : expr) ,*) => { <$ m as Magma >:: operate (& ($ f) , & monoid_fold ! ($ m , $ ($ ff) ,*)) } ; } /// $+$ pub struct AdditiveOperation> { _marker: std::marker::PhantomData T>, } mod additive_operation_impl { use super::*; use std::ops::{Add, Neg, Sub}; impl> Magma for AdditiveOperation { type T = T; #[inline] fn operate(x: &Self::T, y: &Self::T) -> Self::T { x.clone() + y.clone() } } impl> Unital for AdditiveOperation { #[inline] fn unit() -> Self::T { Zero::zero() } } impl> Associative for AdditiveOperation {} impl> Commutative for AdditiveOperation {} impl + Sub + Neg> Invertible for AdditiveOperation { #[inline] fn inverse(x: &Self::T) -> Self::T { -x.clone() } #[inline] fn rinv_operate(x: &Self::T, y: &Self::T) -> Self::T { x.clone() - y.clone() } } } pub trait Zero: Sized { fn zero() -> Self; #[inline] fn is_zero(&self) -> bool where Self: PartialEq, { self == &Self::zero() } #[inline] fn set_zero(&mut self) { *self = Self::zero(); } } pub trait One: Sized { fn one() -> Self; #[inline] fn is_one(&self) -> bool where Self: PartialEq, { self == &Self::one() } #[inline] fn set_one(&mut self) { *self = Self::one(); } } macro_rules ! zero_one_impls { ($ ({ $ Trait : ident $ method : ident $ ($ t : ty) *, $ e : expr }) *) => { $ ($ (impl $ Trait for $ t { fn $ method () -> Self { $ e } }) *) * } ; } zero_one_impls ! ({ Zero zero u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 0 } { Zero zero f32 f64 , 0. } { One one u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 1 } { One one f32 f64 , 1. }); mod tuple_operation_impl { #![allow(unused_variables)] use super::*; macro_rules ! impl_tuple_operation { ($ ($ M : ident) *, $ ($ i : tt) *) => { impl <$ ($ M : Magma) ,*> Magma for ($ ($ M ,) *) { type T = ($ (<$ M as Magma >:: T ,) *) ; # [inline] fn operate (x : & Self :: T , y : & Self :: T) -> Self :: T { ($ (<$ M as Magma >:: operate (& x .$ i , & y .$ i) ,) *) } } impl <$ ($ M : Unital) ,*> Unital for ($ ($ M ,) *) { # [inline] fn unit () -> Self :: T { ($ (<$ M as Unital >:: unit () ,) *) } } impl <$ ($ M : Associative) ,*> Associative for ($ ($ M ,) *) { } impl <$ ($ M : Commutative) ,*> Commutative for ($ ($ M ,) *) { } impl <$ ($ M : Idempotent) ,*> Idempotent for ($ ($ M ,) *) { } impl <$ ($ M : Invertible) ,*> Invertible for ($ ($ M ,) *) { # [inline] fn inverse (x : & Self :: T) -> Self :: T { ($ (<$ M as Invertible >:: inverse (& x .$ i) ,) *) } } } ; } impl_tuple_operation ! (,); impl_tuple_operation!(A, 0); impl_tuple_operation ! (A B , 0 1); impl_tuple_operation ! (A B C , 0 1 2); impl_tuple_operation ! (A B C D , 0 1 2 3); impl_tuple_operation ! (A B C D E , 0 1 2 3 4); impl_tuple_operation ! (A B C D E F , 0 1 2 3 4 5); impl_tuple_operation ! (A B C D E F G , 0 1 2 3 4 5 6); impl_tuple_operation ! (A B C D E F G H , 0 1 2 3 4 5 6 7); impl_tuple_operation ! (A B C D E F G H I , 0 1 2 3 4 5 6 7 8); impl_tuple_operation ! (A B C D E F G H I J , 0 1 2 3 4 5 6 7 8 9); } pub mod mint_basic { use super::*; #[macro_export] macro_rules ! define_basic_mintbase { ($ name : ident , $ m : expr , $ basety : ty , $ signedty : ty , $ upperty : ty , [$ ($ unsigned : ty) ,*] , [$ ($ signed : ty) ,*]) => { pub struct $ name ; impl MIntBase for $ name { type Inner = $ basety ; # [inline] fn get_mod () -> Self :: Inner { $ m } # [inline] fn mod_zero () -> Self :: Inner { 0 } # [inline] fn mod_one () -> Self :: Inner { 1 } # [inline] fn mod_add (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { let z = x + y ; let m = Self :: get_mod () ; if z >= m { z - m } else { z } } # [inline] fn mod_sub (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { if x < y { x + Self :: get_mod () - y } else { x - y } } # [inline] fn mod_mul (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { (x as $ upperty * y as $ upperty % Self :: get_mod () as $ upperty) as $ basety } # [inline] fn mod_div (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { Self :: mod_mul (x , Self :: mod_inv (y)) } # [inline] fn mod_neg (x : Self :: Inner) -> Self :: Inner { if x == 0 { 0 } else { Self :: get_mod () - x } } fn mod_inv (x : Self :: Inner) -> Self :: Inner { let p = Self :: get_mod () as $ signedty ; let (mut a , mut b) = (x as $ signedty , p) ; let (mut u , mut x) = (1 , 0) ; while a != 0 { let k = b / a ; x -= k * u ; b -= k * a ; std :: mem :: swap (& mut x , & mut u) ; std :: mem :: swap (& mut b , & mut a) ; } (if x < 0 { x + p } else { x }) as _ } } $ (impl MIntConvert <$ unsigned > for $ name { # [inline] fn from (x : $ unsigned) -> Self :: Inner { (x % < Self as MIntBase >:: get_mod () as $ unsigned) as $ basety } # [inline] fn into (x : Self :: Inner) -> $ unsigned { x as $ unsigned } # [inline] fn mod_into () -> $ unsigned { < Self as MIntBase >:: get_mod () as $ unsigned } }) * $ (impl MIntConvert <$ signed > for $ name { # [inline] fn from (x : $ signed) -> Self :: Inner { let x = x % < Self as MIntBase >:: get_mod () as $ signed ; if x < 0 { (x + < Self as MIntBase >:: get_mod () as $ signed) as $ basety } else { x as $ basety } } # [inline] fn into (x : Self :: Inner) -> $ signed { x as $ signed } # [inline] fn mod_into () -> $ signed { < Self as MIntBase >:: get_mod () as $ signed } }) * } ; } #[macro_export] macro_rules ! define_basic_mint32 { ($ ([$ name : ident , $ m : expr , $ mint_name : ident]) ,*) => { $ (crate :: define_basic_mintbase ! ($ name , $ m , u32 , i32 , u64 , [u32 , u64 , u128 , usize] , [i32 , i64 , i128 , isize]) ; pub type $ mint_name = MInt <$ name >;) * } ; } define_basic_mint32!( [Modulo998244353, 998_244_353, MInt998244353], [Modulo1000000007, 1_000_000_007, MInt1000000007], [Modulo1000000009, 1_000_000_009, MInt1000000009], [ DynModuloU32, DYN_MODULUS_U32.with(|cell| unsafe { *cell.get() }), DynMIntU32 ] ); thread_local ! (static DYN_MODULUS_U32 : std :: cell :: UnsafeCell < u32 > = std :: cell :: UnsafeCell :: new (1_000_000_007)); impl DynModuloU32 { pub fn set_mod(m: u32) { DYN_MODULUS_U32.with(|cell| unsafe { *cell.get() = m }) } } thread_local ! (static DYN_MODULUS_U64 : std :: cell :: UnsafeCell < u64 > = std :: cell :: UnsafeCell :: new (1_000_000_007)); define_basic_mintbase!( DynModuloU64, DYN_MODULUS_U64.with(|cell| unsafe { *cell.get() }), u64, i64, u128, [u64, u128, usize], [i64, i128, isize] ); impl DynModuloU64 { pub fn set_mod(m: u64) { DYN_MODULUS_U64.with(|cell| unsafe { *cell.get() = m }) } } pub type DynMIntU64 = MInt; pub struct Modulo2; impl MIntBase for Modulo2 { type Inner = u32; #[inline] fn get_mod() -> Self::Inner { 2 } #[inline] fn mod_zero() -> Self::Inner { 0 } #[inline] fn mod_one() -> Self::Inner { 1 } #[inline] fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner { x ^ y } #[inline] fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner { x ^ y } #[inline] fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner { x | y } #[inline] fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner { assert_ne!(y, 0); x } #[inline] fn mod_neg(x: Self::Inner) -> Self::Inner { x } #[inline] fn mod_inv(x: Self::Inner) -> Self::Inner { assert_ne!(x, 0); x } #[inline] fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner { if y == 0 { 1 } else { x } } } macro_rules ! impl_to_mint_base_for_modulo2 { ($ name : ident , $ basety : ty , [$ ($ t : ty) ,*]) => { $ (impl MIntConvert <$ t > for $ name { # [inline] fn from (x : $ t) -> Self :: Inner { (x & 1) as $ basety } # [inline] fn into (x : Self :: Inner) -> $ t { x as $ t } # [inline] fn mod_into () -> $ t { 1 } }) * } ; } impl_to_mint_base_for_modulo2!( Modulo2, u32, [u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize] ); pub type MInt2 = MInt; } #[repr(transparent)] pub struct MInt where M: MIntBase, { x: M::Inner, _marker: std::marker::PhantomData M>, } pub trait MIntBase { type Inner: Sized + Copy + Eq + std::fmt::Debug + std::hash::Hash; fn get_mod() -> Self::Inner; fn mod_zero() -> Self::Inner; fn mod_one() -> Self::Inner; fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner; fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner; fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner; fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner; fn mod_neg(x: Self::Inner) -> Self::Inner; fn mod_inv(x: Self::Inner) -> Self::Inner; fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner { let (mut x, mut y, mut z) = (x, y, Self::mod_one()); while y > 0 { if y & 1 == 1 { z = Self::mod_mul(z, x); } x = Self::mod_mul(x, x); y >>= 1; } z } } pub trait MIntConvert::Inner>: MIntBase { fn from(x: T) -> ::Inner; fn into(x: ::Inner) -> T; fn mod_into() -> T; } mod mint_base { use super::*; use std::{ fmt::{self, Debug, Display}, hash::{Hash, Hasher}, iter::{Product, Sum}, marker::PhantomData, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, str::FromStr, }; impl MInt where M: MIntConvert, { #[inline] pub fn new(x: M::Inner) -> Self { Self::new_unchecked(>::from(x)) } #[inline] pub fn inner(self) -> M::Inner { >::into(self.x) } } impl MInt where M: MIntBase, { #[inline] pub fn new_unchecked(x: M::Inner) -> Self { Self { x, _marker: PhantomData, } } #[inline] pub fn get_mod() -> M::Inner { M::get_mod() } #[inline] pub fn pow(self, y: usize) -> Self { Self::new_unchecked(M::mod_pow(self.x, y)) } #[inline] pub fn inv(self) -> Self { Self::new_unchecked(M::mod_inv(self.x)) } } impl Clone for MInt where M: MIntBase, { #[inline] fn clone(&self) -> Self { Self { x: Clone::clone(&self.x), _marker: PhantomData, } } } impl Copy for MInt where M: MIntBase {} impl Debug for MInt where M: MIntBase, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Debug::fmt(&self.x, f) } } impl Default for MInt where M: MIntBase, { #[inline] fn default() -> Self { ::zero() } } impl PartialEq for MInt where M: MIntBase, { #[inline] fn eq(&self, other: &Self) -> bool { PartialEq::eq(&self.x, &other.x) } } impl Eq for MInt where M: MIntBase {} impl Hash for MInt where M: MIntBase, { #[inline] fn hash(&self, state: &mut H) { Hash::hash(&self.x, state) } } macro_rules ! impl_mint_from { ($ ($ t : ty) ,*) => { $ (impl < M > From <$ t > for MInt < M > where M : MIntConvert <$ t >, { # [inline] fn from (x : $ t) -> Self { Self :: new_unchecked (< M as MIntConvert <$ t >>:: from (x)) } } impl < M > From < MInt < M >> for $ t where M : MIntConvert <$ t >, { # [inline] fn from (x : MInt < M >) -> $ t { < M as MIntConvert <$ t >>:: into (x . x) } }) * } ; } impl_mint_from!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize); impl Zero for MInt where M: MIntBase, { #[inline] fn zero() -> Self { Self::new_unchecked(M::mod_zero()) } } impl One for MInt where M: MIntBase, { #[inline] fn one() -> Self { Self::new_unchecked(M::mod_one()) } } impl Add for MInt where M: MIntBase, { type Output = Self; #[inline] fn add(self, rhs: Self) -> Self::Output { Self::new_unchecked(M::mod_add(self.x, rhs.x)) } } impl Sub for MInt where M: MIntBase, { type Output = Self; #[inline] fn sub(self, rhs: Self) -> Self::Output { Self::new_unchecked(M::mod_sub(self.x, rhs.x)) } } impl Mul for MInt where M: MIntBase, { type Output = Self; #[inline] fn mul(self, rhs: Self) -> Self::Output { Self::new_unchecked(M::mod_mul(self.x, rhs.x)) } } impl Div for MInt where M: MIntBase, { type Output = Self; #[inline] fn div(self, rhs: Self) -> Self::Output { Self::new_unchecked(M::mod_div(self.x, rhs.x)) } } impl Neg for MInt where M: MIntBase, { type Output = Self; #[inline] fn neg(self) -> Self::Output { Self::new_unchecked(M::mod_neg(self.x)) } } impl Sum for MInt where M: MIntBase, { #[inline] fn sum>(iter: I) -> Self { iter.fold(::zero(), Add::add) } } impl Product for MInt where M: MIntBase, { #[inline] fn product>(iter: I) -> Self { iter.fold(::one(), Mul::mul) } } impl<'a, M: 'a> Sum<&'a MInt> for MInt where M: MIntBase, { #[inline] fn sum>(iter: I) -> Self { iter.fold(::zero(), Add::add) } } impl<'a, M: 'a> Product<&'a MInt> for MInt where M: MIntBase, { #[inline] fn product>(iter: I) -> Self { iter.fold(::one(), Mul::mul) } } impl Display for MInt where M: MIntConvert, M::Inner: Display, { fn fmt<'a>(&self, f: &mut fmt::Formatter<'a>) -> Result<(), fmt::Error> { write!(f, "{}", self.inner()) } } impl FromStr for MInt where M: MIntConvert, M::Inner: FromStr, { type Err = ::Err; #[inline] fn from_str(s: &str) -> Result { s.parse::().map(Self::new) } } impl IterScan for MInt where M: MIntConvert, M::Inner: FromStr, { type Output = Self; #[inline] fn scan<'a, I: Iterator>(iter: &mut I) -> Option { iter.next()?.parse::>().ok() } } macro_rules! impl_mint_ref_binop { ($ imp : ident , $ method : ident , $ t : ty) => { impl $imp<$t> for &$t where M: MIntBase, { type Output = <$t as $imp<$t>>::Output; #[inline] fn $method(self, other: $t) -> <$t as $imp<$t>>::Output { $imp::$method(*self, other) } } impl $imp<&$t> for $t where M: MIntBase, { type Output = <$t as $imp<$t>>::Output; #[inline] fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output { $imp::$method(self, *other) } } impl $imp<&$t> for &$t where M: MIntBase, { type Output = <$t as $imp<$t>>::Output; #[inline] fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output { $imp::$method(*self, *other) } } }; } impl_mint_ref_binop!(Add, add, MInt); impl_mint_ref_binop!(Sub, sub, MInt); impl_mint_ref_binop!(Mul, mul, MInt); impl_mint_ref_binop!(Div, div, MInt); macro_rules! impl_mint_ref_unop { ($ imp : ident , $ method : ident , $ t : ty) => { impl $imp for &$t where M: MIntBase, { type Output = <$t as $imp>::Output; #[inline] fn $method(self) -> <$t as $imp>::Output { $imp::$method(*self) } } }; } impl_mint_ref_unop!(Neg, neg, MInt); macro_rules! impl_mint_ref_op_assign { ($ imp : ident , $ method : ident , $ t : ty , $ fromimp : ident , $ frommethod : ident) => { impl $imp<$t> for $t where M: MIntBase, { #[inline] fn $method(&mut self, rhs: $t) { *self = $fromimp::$frommethod(*self, rhs); } } impl $imp<&$t> for $t where M: MIntBase, { #[inline] fn $method(&mut self, other: &$t) { $imp::$method(self, *other); } } }; } impl_mint_ref_op_assign!(AddAssign, add_assign, MInt, Add, add); impl_mint_ref_op_assign!(SubAssign, sub_assign, MInt, Sub, sub); impl_mint_ref_op_assign!(MulAssign, mul_assign, MInt, Mul, mul); impl_mint_ref_op_assign!(DivAssign, div_assign, MInt, Div, div); }