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/linear-algebra/pow_of_matrix_matpow.test.py

Depends on

Code

# verification-helper: PROBLEM https://judge.yosupo.jp/problem/pow_of_matrix


def main():
    mod = 998244353
    N, K = read()
    if N < 10:
        from cp_library.math.linalg.mat.mat_pow_fn import mat_pow
        from cp_library.math.mod.mint_cls import mint
        mint.set_mod(998244353)

        A = [read(mint) for _ in range(N)]
        B = mat_pow(A, K)
    else:
        from cp_library.math.linalg.mat.mod.mat_pow_fn import mat_pow

        A = [read() for _ in range(N)]
        B = mat_pow(A, K, mod)

    for row in B:
        write(*row)

from cp_library.io.read_func_fn import read
from cp_library.io.write_fn import write

if __name__ == '__main__':
    main()
# verification-helper: PROBLEM https://judge.yosupo.jp/problem/pow_of_matrix


def main():
    mod = 998244353
    N, K = read()
    if N < 10:
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        
        def mat_pow(A,K):
            R = A if K & 1 else mat_id(len(A))
            for i in range(1,K.bit_length()):
                A = mat_mul(A,A) 
                if K >> i & 1: R = mat_mul(R,A) 
            return R 
        
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        
        def mat_mul(A,B):
            assert len(A[0]) == len(B)
            R = [[0]*len(B[0]) for _ in range(len(A))] 
            for i,Ri in enumerate(R):
                for k,Aik in enumerate(A[i]):
                    for j,Bkj in enumerate(B[k]):
                        Ri[j] = Bkj*Aik + Ri[j]  
            return R 
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        
        def mat_id(N):
            return [[int(i==j) for j in range(N)] for i in range(N)]
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
            
        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(998244353)

        A = [read(mint) for _ in range(N)]
        B = mat_pow(A, K)
    else:
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        
        def mat_pow(A,K,mod):
            N = len(A)
            ret = A if K & 1 else mat_id(N)
            for i in range(1,K.bit_length()):
                A = mat_mul(A,A,mod) 
                if K >> i & 1:
                    ret = mat_mul(ret,A,mod) 
            return ret 
        
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        
        def mat_mul(A,B,mod):
            assert len(A[0]) == len(B)
            R = [[0]*len(B[0]) for _ in range(len(A))] 
            for i,Ri in enumerate(R):
                for k,Aik in enumerate(A[i]):
                    for j,Bkj in enumerate(B[k]):
                        Ri[j] = (Ri[j] + Aik*Bkj) % mod
            return R
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        
        '''
        ╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
                     https://kobejean.github.io/cp-library               
        '''
        
        def mat_id(N):
            return [[int(i==j) for j in range(N)] for i in range(N)]

        A = [read() for _ in range(N)]
        B = mat_pow(A, K, mod)

    for row in B:
        write(*row)

'''
╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
             https://kobejean.github.io/cp-library               
'''

def read(func=0, /):
    if callable(func): return [func(s) for s in input().split()]
    return [int(s)+func for s in input().split()]
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)

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()

if __name__ == '__main__':
    main()
Back to top page