cp-library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub kobejean/cp-library

:heavy_check_mark: test/library-checker/set-power-series/subset_convolution_all.test.py

Depends on

Code

# verification-helper: PROBLEM https://judge.yosupo.jp/problem/subset_convolution
from cp_library.io.read_fn import read
from cp_library.io.write_fn import write
mod = 998244353

N, = read()
if N < 10:
    from cp_library.math.conv.subset_conv_fn import subset_conv
    from cp_library.math.mod.mint_cls import mint
    mint.set_mod(mod)
    F = read(list[mint])
    G = read(list[mint])
    write(*subset_conv(F, G, N))
else:
    from cp_library.math.conv.mod.subset_conv_fn import subset_conv
    
    F = read(list[int])
    G = read(list[int])
    write(*subset_conv(F, G, N, mod))
# verification-helper: PROBLEM https://judge.yosupo.jp/problem/subset_convolution
'''
╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
             https://kobejean.github.io/cp-library               
'''

from typing import Iterable, Type, Union, overload
import typing
from collections import deque
from numbers import Number
from types import GenericAlias 
from typing import Callable, Collection, Iterator, Union
import os
import sys
from io import BytesIO, IOBase


class FastIO(IOBase):
    BUFSIZE = 8192
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        BUFSIZE = self.BUFSIZE
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        BUFSIZE = self.BUFSIZE
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    stdin: 'IOWrapper' = None
    stdout: 'IOWrapper' = None
    
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable

    def write(self, s):
        return self.buffer.write(s.encode("ascii"))
    
    def read(self):
        return self.buffer.read().decode("ascii")
    
    def readline(self):
        return self.buffer.readline().decode("ascii")

sys.stdin = IOWrapper.stdin = IOWrapper(sys.stdin)
sys.stdout = IOWrapper.stdout = IOWrapper(sys.stdout)
from typing import TypeVar
_T = TypeVar('T')

class TokenStream(Iterator):
    stream = IOWrapper.stdin

    def __init__(self):
        self.queue = deque()

    def __next__(self):
        if not self.queue: self.queue.extend(self._line())
        return self.queue.popleft()
    
    def wait(self):
        if not self.queue: self.queue.extend(self._line())
        while self.queue: yield
 
    def _line(self):
        return TokenStream.stream.readline().split()

    def line(self):
        if self.queue:
            A = list(self.queue)
            self.queue.clear()
            return A
        return self._line()
TokenStream.default = TokenStream()

class CharStream(TokenStream):
    def _line(self):
        return TokenStream.stream.readline().rstrip()
CharStream.default = CharStream()


ParseFn = Callable[[TokenStream],_T]
class Parser:
    def __init__(self, spec: Union[type[_T],_T]):
        self.parse = Parser.compile(spec)

    def __call__(self, ts: TokenStream) -> _T:
        return self.parse(ts)
    
    @staticmethod
    def compile_type(cls: type[_T], args = ()) -> _T:
        if issubclass(cls, Parsable):
            return cls.compile(*args)
        elif issubclass(cls, (Number, str)):
            def parse(ts: TokenStream): return cls(next(ts))              
            return parse
        elif issubclass(cls, tuple):
            return Parser.compile_tuple(cls, args)
        elif issubclass(cls, Collection):
            return Parser.compile_collection(cls, args)
        elif callable(cls):
            def parse(ts: TokenStream):
                return cls(next(ts))              
            return parse
        else:
            raise NotImplementedError()
    
    @staticmethod
    def compile(spec: Union[type[_T],_T]=int) -> ParseFn[_T]:
        if isinstance(spec, (type, GenericAlias)):
            cls = typing.get_origin(spec) or spec
            args = typing.get_args(spec) or tuple()
            return Parser.compile_type(cls, args)
        elif isinstance(offset := spec, Number): 
            cls = type(spec)  
            def parse(ts: TokenStream): return cls(next(ts)) + offset
            return parse
        elif isinstance(args := spec, tuple):      
            return Parser.compile_tuple(type(spec), args)
        elif isinstance(args := spec, Collection):  
            return Parser.compile_collection(type(spec), args)
        elif isinstance(fn := spec, Callable): 
            def parse(ts: TokenStream): return fn(next(ts))
            return parse
        else:
            raise NotImplementedError()

    @staticmethod
    def compile_line(cls: _T, spec=int) -> ParseFn[_T]:
        if spec is int:
            fn = Parser.compile(spec)
            def parse(ts: TokenStream): return cls([int(token) for token in ts.line()])
            return parse
        else:
            fn = Parser.compile(spec)
            def parse(ts: TokenStream): return cls([fn(ts) for _ in ts.wait()])
            return parse

    @staticmethod
    def compile_repeat(cls: _T, spec, N) -> ParseFn[_T]:
        fn = Parser.compile(spec)
        def parse(ts: TokenStream): return cls([fn(ts) for _ in range(N)])
        return parse

    @staticmethod
    def compile_children(cls: _T, specs) -> ParseFn[_T]:
        fns = tuple((Parser.compile(spec) for spec in specs))
        def parse(ts: TokenStream): return cls([fn(ts) for fn in fns])  
        return parse
            
    @staticmethod
    def compile_tuple(cls: type[_T], specs) -> ParseFn[_T]:
        if isinstance(specs, (tuple,list)) and len(specs) == 2 and specs[1] is ...:
            return Parser.compile_line(cls, specs[0])
        else:
            return Parser.compile_children(cls, specs)

    @staticmethod
    def compile_collection(cls, specs):
        if not specs or len(specs) == 1 or isinstance(specs, set):
            return Parser.compile_line(cls, *specs)
        elif (isinstance(specs, (tuple,list)) and len(specs) == 2 and isinstance(specs[1], int)):
            return Parser.compile_repeat(cls, specs[0], specs[1])
        else:
            raise NotImplementedError()

class Parsable:
    @classmethod
    def compile(cls):
        def parser(ts: TokenStream): return cls(next(ts))
        return parser

@overload
def read() -> Iterable[int]: ...
@overload
def read(spec: int) -> list[int]: ...
@overload
def read(spec: Union[Type[_T],_T], char=False) -> _T: ...
def read(spec: Union[Type[_T],_T] = None, char=False):
    if not char and spec is None: return map(int, TokenStream.default.line())
    parser: _T = Parser.compile(spec)
    return parser(CharStream.default if char else TokenStream.default)

def write(*args, **kwargs):
    '''Prints the values to a stream, or to stdout_fast by default.'''
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", IOWrapper.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()
mod = 998244353

N, = read()
if N < 10:
    
    
    def popcnts(N):
        P = [0]*(1 << N)
        for i in range(N):
            for m in range(b := 1<<i):
                P[m^b] = P[m] + 1
        return P
    
    '''
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
        x₀ ────────●─●────────●───●────────●───────●────────► X₀
                    ╳          ╲ ╱          ╲     ╱          
        x₄ ────────●─●────────●─╳─●────────●─╲───╱─●────────► X₁
                               ╳ ╳          ╲ ╲ ╱ ╱          
        x₂ ────────●─●────────●─╳─●────────●─╲─╳─╱─●────────► X₂
                    ╳          ╱ ╲          ╲ ╳ ╳ ╱          
        x₆ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₃
                                            ╳ ╳ ╳ ╳         
        x₁ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₄
                    ╳          ╲ ╱          ╱ ╳ ╳ ╲          
        x₅ ────────●─●────────●─╳─●────────●─╱─╳─╲─●────────► X₅
                               ╳ ╳          ╱ ╱ ╲ ╲          
        x₃ ────────●─●────────●─╳─●────────●─╱───╲─●────────► X₆
                    ╳          ╱ ╲          ╱     ╲          
        x₇ ────────●─●────────●───●────────●───────●────────► X₇
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                          Math - Convolution                     
    '''
    
    '''
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
        x₀ ────────●─●────────●───●────────●───────●────────► X₀
                    ╳          ╲ ╱          ╲     ╱          
        x₄ ────────●─●────────●─╳─●────────●─╲───╱─●────────► X₁
                               ╳ ╳          ╲ ╲ ╱ ╱          
        x₂ ────────●─●────────●─╳─●────────●─╲─╳─╱─●────────► X₂
                    ╳          ╱ ╲          ╲ ╳ ╳ ╱          
        x₆ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₃
                                            ╳ ╳ ╳ ╳         
        x₁ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₄
                    ╳          ╲ ╱          ╱ ╳ ╳ ╲          
        x₅ ────────●─●────────●─╳─●────────●─╱─╳─╲─●────────► X₅
                               ╳ ╳          ╱ ╱ ╲ ╲          
        x₃ ────────●─●────────●─╳─●────────●─╱───╲─●────────► X₆
                    ╳          ╱ ╲          ╱     ╲          
        x₇ ────────●─●────────●───●────────●───────●────────► X₇
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                          Math - Convolution                     
    '''
    
    def subset_zeta_pair(A: list[int], B: list[int], N: int):
        Z = len(A)
        for i in range(N):
            m = b = 1<<i
            while m < Z:
                A[m] += A[m^b]
                B[m] += B[m^b]
                m = m+1|b
        return A, B
    
    '''
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
        x₀ ────────●─●────────●───●────────●───────●────────► X₀
                    ╳          ╲ ╱          ╲     ╱          
        x₄ ────────●─●────────●─╳─●────────●─╲───╱─●────────► X₁
                               ╳ ╳          ╲ ╲ ╱ ╱          
        x₂ ────────●─●────────●─╳─●────────●─╲─╳─╱─●────────► X₂
                    ╳          ╱ ╲          ╲ ╳ ╳ ╱          
        x₆ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₃
                                            ╳ ╳ ╳ ╳         
        x₁ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₄
                    ╳          ╲ ╱          ╱ ╳ ╳ ╲          
        x₅ ────────●─●────────●─╳─●────────●─╱─╳─╲─●────────► X₅
                               ╳ ╳          ╱ ╱ ╲ ╲          
        x₃ ────────●─●────────●─╳─●────────●─╱───╲─●────────► X₆
                    ╳          ╱ ╲          ╱     ╲          
        x₇ ────────●─●────────●───●────────●───────●────────► X₇
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                          Math - Convolution                     
    '''
    
    def subset_mobius(A: list[int], N: int):
        Z = len(A)
        for i in range(N):
            m = b = 1<<i
            while m < Z:
                A[m] -= A[m^b]
                m = m+1|b
        return A
    
    def subset_conv(A,B,N):
        assert len(A) == len(B)
        Z = (N+1)*(M := 1<<N)
        Ar,Br,Cr,P = [0]*Z, [0]*Z, [0]*Z, popcnts(N)
        for i,p in enumerate(P): Ar[p<<N|i], Br[p<<N|i] = A[i], B[i]
        subset_zeta_pair(Ar, Br, N)
        for i in range(0,Z,M):
            for j in range(0,Z-i,M):
                ij = i+j
                for k in range(M): Cr[ij|k] += Ar[i|k] * Br[j|k]
        subset_mobius(Cr, N)
        for i,p in enumerate(P): A[i] = Cr[p<<N|i]
        return A
    
        
    class mint(int):
        mod: int
        zero: 'mint'
        one: 'mint'
        two: 'mint'
        cache: list['mint']
    
        def __new__(cls, *args, **kwargs):
            if 0<= (x := int(*args, **kwargs)) <= 2:
                return cls.cache[x]
            else:
                return cls.fix(x)
    
        @classmethod
        def set_mod(cls, mod: int):
            mint.mod = cls.mod = mod
            mint.zero = cls.zero = cls.cast(0)
            mint.one = cls.one = cls.fix(1)
            mint.two = cls.two = cls.fix(2)
            mint.cache = cls.cache = [cls.zero, cls.one, cls.two]
    
        @classmethod
        def fix(cls, x): return cls.cast(x%cls.mod)
    
        @classmethod
        def cast(cls, x): return super().__new__(cls,x)
    
        @classmethod
        def mod_inv(cls, x):
            a,b,s,t = int(x), cls.mod, 1, 0
            while b: a,b,s,t = b,a%b,t,s-a//b*t
            if a == 1: return cls.fix(s)
            raise ValueError(f"{x} is not invertible in mod {cls.mod}")
        
        @property
        def inv(self): return mint.mod_inv(self)
    
        def __add__(self, x): return mint.fix(super().__add__(x))
        def __radd__(self, x): return mint.fix(super().__radd__(x))
        def __sub__(self, x): return mint.fix(super().__sub__(x))
        def __rsub__(self, x): return mint.fix(super().__rsub__(x))
        def __mul__(self, x): return mint.fix(super().__mul__(x))
        def __rmul__(self, x): return mint.fix(super().__rmul__(x))
        def __floordiv__(self, x): return self * mint.mod_inv(x)
        def __rfloordiv__(self, x): return self.inv * x
        def __truediv__(self, x): return self * mint.mod_inv(x)
        def __rtruediv__(self, x): return self.inv * x
        def __pow__(self, x): 
            return self.cast(super().__pow__(x, self.mod))
        def __neg__(self): return mint.mod-self
        def __pos__(self): return self
        def __abs__(self): return self
    mint.set_mod(mod)
    F = read(list[mint])
    G = read(list[mint])
    write(*subset_conv(F, G, N))
else:
    
    '''
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
        x₀ ────────●─●────────●───●────────●───────●────────► X₀
                    ╳          ╲ ╱          ╲     ╱          
        x₄ ────────●─●────────●─╳─●────────●─╲───╱─●────────► X₁
                               ╳ ╳          ╲ ╲ ╱ ╱          
        x₂ ────────●─●────────●─╳─●────────●─╲─╳─╱─●────────► X₂
                    ╳          ╱ ╲          ╲ ╳ ╳ ╱          
        x₆ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₃
                                            ╳ ╳ ╳ ╳         
        x₁ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₄
                    ╳          ╲ ╱          ╱ ╳ ╳ ╲          
        x₅ ────────●─●────────●─╳─●────────●─╱─╳─╲─●────────► X₅
                               ╳ ╳          ╱ ╱ ╲ ╲          
        x₃ ────────●─●────────●─╳─●────────●─╱───╲─●────────► X₆
                    ╳          ╱ ╲          ╱     ╲          
        x₇ ────────●─●────────●───●────────●───────●────────► X₇
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                          Math - Convolution                     
    '''
    
    
    
    def popcnts(N):
        P = [0]*(1 << N)
        for i in range(N):
            for m in range(b := 1<<i):
                P[m^b] = P[m] + 1
        return P
    
    '''
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
        x₀ ────────●─●────────●───●────────●───────●────────► X₀
                    ╳          ╲ ╱          ╲     ╱          
        x₄ ────────●─●────────●─╳─●────────●─╲───╱─●────────► X₁
                               ╳ ╳          ╲ ╲ ╱ ╱          
        x₂ ────────●─●────────●─╳─●────────●─╲─╳─╱─●────────► X₂
                    ╳          ╱ ╲          ╲ ╳ ╳ ╱          
        x₆ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₃
                                            ╳ ╳ ╳ ╳         
        x₁ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₄
                    ╳          ╲ ╱          ╱ ╳ ╳ ╲          
        x₅ ────────●─●────────●─╳─●────────●─╱─╳─╲─●────────► X₅
                               ╳ ╳          ╱ ╱ ╲ ╲          
        x₃ ────────●─●────────●─╳─●────────●─╱───╲─●────────► X₆
                    ╳          ╱ ╲          ╱     ╲          
        x₇ ────────●─●────────●───●────────●───────●────────► X₇
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                          Math - Convolution                     
    '''
    
    '''
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
        x₀ ────────●─●────────●───●────────●───────●────────► X₀
                    ╳          ╲ ╱          ╲     ╱          
        x₄ ────────●─●────────●─╳─●────────●─╲───╱─●────────► X₁
                               ╳ ╳          ╲ ╲ ╱ ╱          
        x₂ ────────●─●────────●─╳─●────────●─╲─╳─╱─●────────► X₂
                    ╳          ╱ ╲          ╲ ╳ ╳ ╱          
        x₆ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₃
                                            ╳ ╳ ╳ ╳         
        x₁ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₄
                    ╳          ╲ ╱          ╱ ╳ ╳ ╲          
        x₅ ────────●─●────────●─╳─●────────●─╱─╳─╲─●────────► X₅
                               ╳ ╳          ╱ ╱ ╲ ╲          
        x₃ ────────●─●────────●─╳─●────────●─╱───╲─●────────► X₆
                    ╳          ╱ ╲          ╱     ╲          
        x₇ ────────●─●────────●───●────────●───────●────────► X₇
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                          Math - Convolution                     
    '''
    
    def subset_zeta_pair(A: list[int], B: list[int], N: int):
        Z = len(A)
        for i in range(N):
            m = b = 1<<i
            while m < Z:
                A[m] += A[m^b]
                B[m] += B[m^b]
                m = m+1|b
        return A, B
    
    '''
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
        x₀ ────────●─●────────●───●────────●───────●────────► X₀
                    ╳          ╲ ╱          ╲     ╱          
        x₄ ────────●─●────────●─╳─●────────●─╲───╱─●────────► X₁
                               ╳ ╳          ╲ ╲ ╱ ╱          
        x₂ ────────●─●────────●─╳─●────────●─╲─╳─╱─●────────► X₂
                    ╳          ╱ ╲          ╲ ╳ ╳ ╱          
        x₆ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₃
                                            ╳ ╳ ╳ ╳         
        x₁ ────────●─●────────●───●────────●─╳─╳─╳─●────────► X₄
                    ╳          ╲ ╱          ╱ ╳ ╳ ╲          
        x₅ ────────●─●────────●─╳─●────────●─╱─╳─╲─●────────► X₅
                               ╳ ╳          ╱ ╱ ╲ ╲          
        x₃ ────────●─●────────●─╳─●────────●─╱───╲─●────────► X₆
                    ╳          ╱ ╲          ╱     ╲          
        x₇ ────────●─●────────●───●────────●───────●────────► X₇
    ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                          Math - Convolution                     
    '''
    
    def subset_mobius(A: list[int], N: int):
        Z = len(A)
        for i in range(N):
            m = b = 1<<i
            while m < Z:
                A[m] -= A[m^b]
                m = m+1|b
        return A
    
    
    def isubset_conv(A: list[int], B: list[int], N: int, mod: int) -> list[int]:
        assert len(A) == len(B)
        Z = (N+1)*(M := 1<<N)
        Ar,Br,Cr,P = [0]*Z, [0]*Z, [0]*Z, popcnts(N)
        for i,p in enumerate(P): Ar[p<<N|i], Br[p<<N|i] = A[i], B[i]
        subset_zeta_pair(Ar, Br, N)
        for i in range(Z): Ar[i], Br[i] = Ar[i]%mod, Br[i]%mod
        for i in range(0,Z,M):
            for j in range(0,Z-i,M):
                ij = i+j
                for k in range(M): Cr[ijk] = (Cr[ijk:=ij|k] + Ar[i|k] * Br[j|k]) % mod
        subset_mobius(Cr, N)
        for i,p in enumerate(P): A[i] = Cr[p<<N|i] % mod
        return A
    
    def subset_conv(A: list[int], B: list[int], N: int, mod: int) -> list[int]:
        return isubset_conv(A[:], B, N, mod)
    
    F = read(list[int])
    G = read(list[int])
    write(*subset_conv(F, G, N, mod))
Back to top page