Problem:


Score : 100 points

Problem Statement

There is a simple directed graph G with N vertices, numbered 1, 2, \ldots, N.

For each i and j (1 \leq i, j \leq N), you are given an integer a_{i, j} that represents whether there is a directed edge from Vertex i to j.
If a_{i, j} = 1, there is a directed edge from Vertex i to j; if a_{i, j} = 0, there is not.

Find the number of different directed paths of length K in G, modulo 10^9 + 7.
We will also count a path that traverses the same edge multiple times.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 10^{18}

a_{i, j} is 0 or 1.

a_{i, i} = 0

Input

Input is given from Standard Input in the following format:

N K
a_{1, 1} \ldots a_{1, N}
:
a_{N, 1} \ldots a_{N, N}

Output

Print the number of different directed paths of length K in G, modulo 10^9 + 7.

Sample Input 1

4 2
0 1 0 0
0 0 1 1
0 0 0 1
1 0 0 0

Sample Output 1

6

G is drawn in the figure below:

There are six directed paths of length 2:

1 → 2 → 3

1 → 2 → 4

2 → 3 → 4

2 → 4 → 1

3 → 4 → 1

4 → 1 → 2

Sample Input 2

3 3
0 1 0
1 0 1
0 0 0

Sample Output 2

3

G is drawn in the figure below:

There are three directed paths of length 3:

1 → 2 → 1 → 2

2 → 1 → 2 → 1

2 → 1 → 2 → 3

Sample Input 3

6 2
0 0 0 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0
0 0 0 0 1 0
0 0 0 0 0 1
0 0 0 0 0 0

Sample Output 3

1

G is drawn in the figure below:

There is one directed path of length 2:

4 → 5 → 6

Sample Input 4

1 1
0

Sample Output 4

0

Sample Input 5

10 1000000000000000000
0 0 1 1 0 0 0 1 1 0
0 0 0 0 0 1 1 1 0 0
0 1 0 0 0 1 0 1 0 1
1 1 1 0 1 1 0 1 1 0
0 1 1 1 0 1 0 1 1 1
0 0 0 1 0 0 1 0 1 0
0 0 0 1 1 0 0 1 0 1
1 0 0 0 1 0 1 0 0 0
0 0 0 0 0 1 0 0 0 0
1 0 1 1 1 0 1 1 1 0

Sample Output 5

957538352

Be sure to print the count modulo 10^9 + 7.



Sample input:
4 2
0 1 0 0
0 0 1 1
0 0 0 1
1 0 0 0


Sample output:
6

Submission status: Wrong Answer

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in R(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()

########################################################################################################################################################################
# Verified by 
# https://atcoder.jp/contests/abc014/tasks/abc014_4
# https://atcoder.jp/contests/abc133/tasks/abc133_f

# import SparseTable
# initialize
# Tree() => n; (a,b);*(n-1)
# Tree(n) => (a,b);*(n-1)
# Tree(init=False); Tree.stdin(); => n; (a,b);*(n-1)
# Tree(init=False); Tree.listin(ls,index=0); => (a,b);*(n-1)

import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
read=sys.stdin.buffer.read
readline=sys.stdin.buffer.readline
input=lambda: sys.stdin.readline().rstrip()

## Verified by Yukicoder 1073
## https://yukicoder.me/problems/no/1073
##
## Matrix Class supporting operators +, -, *, %, +=, -=, *=, %=
## *, *= allows int/float/complex
## ** or pow(self,p,mod) for the size N*N matrix is implemented by Repeated squaring. O(N^3*log(p))
##
## Constructor: matrix(array), where array is 1D or 2D array. 1-dimensional array X is modified as 2D array of [X].
##
## methods
## T(): returns transposed matrix
## resize((n,m),fill=0): changes the matrix instance into the new shape (n * m), missing entries are filled with "fill" (default value is zero).


class matrix:
    class MulShapeError(Exception):
        "mult is not applicable between the two matrices given"
        pass

    def __init__(self,arr_input):
        if hasattr(arr_input[0],"__getitem__"):
            self.arr=arr_input
        else:
            self.arr=[arr_input]
        self.shape=(len(self.arr),len(self.arr[0]))

    def __getitem__(self,key):
        return self.arr[key]

    def __setitem__(self,key,value):
        self.arr[key]=value

    def __iter__(self):
        return iter(self.arr)
        
    def __add__(self,B):
        if type(B)!=matrix:
            return NotImplemented
        if B.shape!=self.shape:
            return NotImplemented
        rt=[[0]*self.shape[1] for i in range(self.shape[0])]
        for i in range(self.shape[0]):
            for j in range(self.shape[1]):
                rt[i][j]=self.arr[i][j]+B.arr[i][j]
        return matrix(rt)

    def __iadd__(self,B):
        return self.__add__(B)

    def __sub__(self,B):
        if type(B)!=matrix:
            return NotImplemented
        if B.shape!=self.shape:
            return NotImplemented
        rt=[[0]*self.shape[1] for i in range(self.shape[0])]
        for i in range(self.shape[0]):
            for j in range(self.shape[1]):
                rt[i][j]=self.arr[i][j]-B.arr[i][j]
        return matrix(rt)

    def __isub__(self,B):
        return self.__sub__(B)

    def __mul__(self,M):
        if type(M) in [int,float,complex]:
            M=matrix([[M*(i==j) for j in range(self.shape[1])] for i in range(self.shape[1])])
        if type(M)!=matrix:
            return NotImplemented
        if M.shape[0]!=self.shape[1]:
            raise matrix.MulShapeError("mult is not applicable between the matrices of shape "+str(self.shape)+" and "+str(M.shape))
        ra,ca=self.shape
        rb,cb=M.shape
        c=[[0]*cb for i in range(ra)]
        for i in range(ra):
            for j in range(cb):
                for k in range(ca):
                    c[i][j]+=self.arr[i][k]*M.arr[k][j]
        return matrix(c)

    def __imul__(self,M):
        return self.__mul__(M)

    def __rmul__(self,M):
        if type(M) in [int,float,complex]:
            M=matrix([[M*(i==j) for j in range(self.shape[1])] for i in range(self.shape[1])])
        if type(M)!=matrix:
            return NotImplemented
        if M.shape[0]!=self.shape[1]:
            raise matrix.MulShapeError("mult is not applicable between the matrix shape "+str(self.shape)+" and "+str(M.shape))
        ra,ca=M.shape
        rb,cb=self.shape
        c=[[0]*cb for i in range(ra)]
        for i in range(ra):
            for j in range(cb):
                for k in range(ca):
                    c[i][j]+=M.arr[i][k]*self.arr[k][j]
        return matrix(c)

    def __mod__(self,p):
        if type(p)!=int:
            return NotImplemented
        c=[[0]*self.shape[1] for i in range(self.shape[0])]
        for i in range(self.shape[0]):
            for j in range(self.shape[1]):
                c[i][j]=self.arr[i][j]%p
        return matrix(c)

    def __imod__(self,p):
        return self.__mod__(p)

    def __pow__(self,p,mod=10**9+7):
        if type(p)!=int or self.shape[0]!=self.shape[1]:
            return NotImplemented
        A=matrix(self.arr)
        R=matrix([[1*(i==j) for j in range(self.shape[0])] for i in range(self.shape[0])])
        while p>0:
            if p&1:
                R*=A
                R%=mod
            A*=A
            A%=mod
            p>>=1
        return R

    def __neg__(self):
        return self.__mul__(-1)

    def __str__(self):
        rt='['
        for i in self.arr:
            rt=rt+str(i)+",\n"
        return rt[:-2]+']'

    def T(self):
        rt=[[0]*self.shape[0] for i in range(self.shape[1])]
        for i in range(self.shape[0]):
            for j in range(self.shape[1]):
                rt[j][i]=self.arr[i][j]
        return matrix(rt)

    def resize(self,new_shape,fill=0):
        t_arr=[]
        for i in self.arr:
            t_arr+=i
        t_arr.reverse()
        n,m=new_shape
        self.shape=(n,m)
        self.arr=[[fill]*m for i in range(n)]

        for i in range(self.shape[0]):
            for j in range(self.shape[1]):
                if t_arr:
                    self.arr[i][j]=t_arr.pop()
        return

    def view(self):
        for i in self.arr:
            print(i)


show_flg=False
show_flg=True

ans=0

n,k=LI()
a=[]
for i in range(n):
    a+=LI(),
M=matrix(a)
M**=k

print(sum([sum(i)for i in M]))

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np

stdin = sys.stdin


def ni(): return int(ns())


def na(): return list(map(int, stdin.readline().split()))


def naa(N): return [na() for _ in range(N)]


def ns(): return stdin.readline().rstrip()  # ignore trailing spaces


def matrix_pow(A, n, mod=0):
    if n == 1:
        return A
    a = matrix_pow(A, n//2, mod)
    ans = np.dot(a, a)
    ans %= mod
    if n % 2 == 1:
        ans = np.dot(ans, A)
    ans %= mod
    return ans


N, K = na()
A = np.array(naa(N), dtype=np.int64)
mod = 10 ** 9 + 7

B = matrix_pow(A, K, mod)
T = np.array([[1] for _ in range(N)], dtype=np.int64)
ans = np.dot(B, T)
ans %= mod
print(np.sum(ans) % mod)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np

stdin = sys.stdin


def ni(): return int(ns())


def na(): return list(map(int, stdin.readline().split()))


def naa(N): return [na() for _ in range(N)]


def ns(): return stdin.readline().rstrip()  # ignore trailing spaces


def matrix_pow(A, n, mod=0):
    if n == 1:
        return A
    a = matrix_pow(A, n//2, mod)
    ans = np.dot(a, a)
    ans %= mod
    if n % 2 == 1:
        ans = np.dot(ans, A)
    ans %= mod
    return ans


N, K = na()
A = np.array(naa(N))
mod = 10 ** 9 + 7

B = matrix_pow(A, K, mod)
T = np.array([[1] for _ in range(N)])
ans = np.dot(B, T)
ans %= mod
print(np.sum(ans) % mod)

Submission status: Wrong Answer

Solution code:
import numpy as np


MOD = 10**9+7


def mod_matrix_pow(A, n):
    if n == 0:
        return np.eye(A.shape[0], dtype=np.object)
    res = mod_matrix_pow(np.mod(np.dot(A, A).astype(np.int64), MOD), n // 2)
    if n & 1:
        res = np.mod(np.dot(res, A).astype(np.int64), MOD)
    return res


def main():
    N, K = map(int, input().split())
    a = np.array([list(map(int, input().split())) for _ in range(N)])
    
    ans = mod_matrix_pow(a, K)

    print(ans.sum() % MOD)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np


MOD = 10**9+7


def mod_matrix_pow(A, n):
    if n == 0:
        return np.eye(A.shape[0], dtype=np.object)
    res = mod_matrix_pow(np.mod(np.dot(A, A).astype(np.int64), MOD), n // 2)
    if n & 1:
        res = np.mod(np.dot(res, A).astype(np.int64), MOD)
    return res


def main():
    N, K = map(int, input().split())
    a = np.array([list(map(int, input().split())) for _ in range(N)])
    
    ans = mod_matrix_pow(a, K)

    for l in ans:
        print(*l)

    print(ans.sum() % MOD)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np


MOD = 10**9+7


def mod_matrix_pow(A, n):
    if n == 0:
        return np.eye(A.shape[0], dtype=np.int64)
    res = mod_matrix_pow(np.mod(np.dot(A, A), MOD), n // 2)
    if n & 1:
        res = np.mod(np.dot(res, A), MOD)
    return res


def main():
    N, K = map(int, input().split())
    a = np.array([list(map(int, input().split())) for _ in range(N)])
    
    ans = mod_matrix_pow(a, K)

    print(ans.sum() % MOD)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np


MOD = 10**9+7


def mod_matrix_pow(A, n):
    if n == 0:
        return np.eye(A.shape[0], dtype=np.int64)
    res = mod_matrix_pow(np.mod(np.dot(A, A), MOD), n // 2)
    if n & 1:
        res = np.mod(np.dot(res, A), MOD)
    return res


def main():
    N, K = map(int, input().split())
    a = np.array([list(map(int, input().split())) for _ in range(N)])
    
    ans = mod_matrix_pow(a, K)

    print(ans.sum())


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

#from collections import defaultdict
#from heapq import heappush, heappop
import sys
import numpy as np

sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7


def debug(*x):
    print(*x, file=sys.stderr)


def solve(N, K, X):
    powK = np.eye(N, dtype=np.int64)
    while K:
        if K & 1:
            powK = powK.dot(X)
            powK %= MOD
        X = X.dot(X)
        X %= MOD
        K //= 2
    return powK.sum() % MOD


def main():
    # parse input
    N, K = map(int, input().split())
    X = np.int64(read().split())
    X = X.reshape((N, N))
    print(solve(N, K, X))


# tests
T1 = """
4 2
0 1 0 0
0 0 1 1
0 0 0 1
1 0 0 0
"""


def test_T1():
    """
    >>> as_input(T1)
    >>> main()
    6
    """


T2 = """
3 3
0 1 0
1 0 1
0 0 0
"""


def test_T2():
    """
    >>> as_input(T2)
    >>> main()
    3
    """


T5 = """
10 1000000000000000000
0 0 1 1 0 0 0 1 1 0
0 0 0 0 0 1 1 1 0 0
0 1 0 0 0 1 0 1 0 1
1 1 1 0 1 1 0 1 1 0
0 1 1 1 0 1 0 1 1 1
0 0 0 1 0 0 1 0 1 0
0 0 0 1 1 0 0 1 0 1
1 0 0 0 1 0 1 0 0 0
0 0 0 0 0 1 0 0 0 0
1 0 1 1 1 0 1 1 1 0
"""


def test_T5():
    """
    >>> as_input(T5)
    >>> main()
    957538352
    """
# add tests above


def _test():
    import doctest
    doctest.testmod()


def as_input(s):
    "use in test, use given string as input file"
    import io
    global read, input
    f = io.StringIO(s.strip())

    def input():
        return bytes(f.readline(), "ascii")

    def read():
        return bytes(f.read(), "ascii")


USE_NUMBA = False
if (USE_NUMBA and sys.argv[-1] == 'ONLINE_JUDGE') or sys.argv[-1] == '-c':
    print("compiling")
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('solve', solve.__doc__.strip().split()[0])(solve)
    cc.compile()
    exit()
else:
    input = sys.stdin.buffer.readline
    read = sys.stdin.buffer.read

    if (USE_NUMBA and sys.argv[-1] != '-p') or sys.argv[-1] == "--numba":
        # -p: pure python mode
        # if not -p, import compiled module
        from my_module import solve  # pylint: disable=all
    elif sys.argv[-1] == "-t":
        print("testing")
        _test()
        sys.exit()
    elif sys.argv[-1] != '-p' and len(sys.argv) == 2:
        # input given as file
        input_as_file = open(sys.argv[1])
        input = input_as_file.buffer.readline
        read = input_as_file.buffer.read

    main()

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
MOD = 1_000_000_007
N, K = map(int, input().split())
A = np.array(list(map(int, read().split())), dtype='uint64').reshape((N, N))
ans = np.eye(N, dtype='uint64')
while K:
    if K&1:
        np.dot(ans, A ,ans)
        np.mod(ans,MOD,ans)
    np.dot(A, A ,A)
    np.mod(A,MOD,A)
    K >>= 1
print(np.mod(ans.sum(), MOD, dtype='int64'))

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
MOD = 1_000_000_007
N, K = map(int, input().split())
A = np.array(list(map(int, read().split())), dtype='int64').reshape((N, N))
ans = np.eye(N, dtype='int64')
while K:
    if K&1:
        np.dot(ans, A ,ans)
        np.mod(ans,MOD,ans)
    np.dot(A, A ,A)
    np.mod(A,MOD,A)
    K >>= 1
print(ans.sum() % MOD)

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.buffer.readline
import numpy as np
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def matrix_power(A, k, N):
    if k == 0:
        return np.eye(N, dtype=np.int64)
    X = matrix_power(A, k//2, N) % MOD
    X = np.dot(X, X) % MOD
    return np.dot(A, X) % MOD if k&1 else X % MOD

def main():
    N, K = map(int, readline().split())
    A = list(list(map(int, readline().split())) for _ in range(N))
    A = np.array(A, np.int64)
    ans = matrix_power(A,K,N)% MOD
    print(ans.sum() %MOD)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.buffer.readline
import numpy as np
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def matrix_power(A, k, N):
    if k == 0:
        return np.eye(N, dtype=np.int64)
    X = matrix_power(A, k//2, N)
    X = np.dot(X, X) % MOD
    return np.dot(A, X) % MOD if k&1 else X

def main():
    N, K = map(int, readline().split())
    A = list(list(map(int, readline().split())) for _ in range(N))
    A = np.array(A, np.int64)
    ans = matrix_power(A,K,N)
    print(ans.sum() %MOD)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.buffer.readline
import numpy as np
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def matrix_power(A, k, N):
    if k == 0:
        return np.eye(N, dtype=np.int64)
    X = matrix_power(A, k//2, N)
    X = np.dot(X, X) % MOD
    return np.dot(A, X) % MOD if k&1 else X

def main():
    N, K = map(int, readline().split())
    A = list(list(map(int, readline().split())) for _ in range(N))
    A = np.array(A)
    ans = matrix_power(A,K,N)
    print(ans.sum() %MOD)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np
MOD = 10 ** 9 + 7
n, k = map(int, input().split())
a = np.array([list(map(int, input().split())) for _ in range(n)], np.int64)
res = np.eye(n, dtype=np.int64)
while k > 0:
    if k & 1:
        res = np.dot(res, a)
        res %= MOD
    a = np.dot(a, a)
    a %= MOD
    k >>= 1
ans = 0
res.astype(int)
for i in range(n):
    for j in range(n):
        ans += res[i][j]
print(ans % MOD)

Submission status: Wrong Answer

Solution code:
import numpy as np
MOD = 10 ** 9 + 7
n, k = map(int, input().split())
a = np.array([list(map(int, input().split())) for _ in range(n)], dtype='u8')
res = np.eye(n, dtype='u8')
while k > 0:
    if k & 1:
        res = np.dot(res, a)
        res %= MOD
    a = np.dot(a, a)
    a %= MOD
    k >>= 1
ans = 0
for i in range(n):
    ans += int(res[i].sum())
print(ans % MOD)

Submission status: Wrong Answer

Solution code:
import numpy as np
MOD = 10 ** 9 + 7
n, k = map(int, input().split())
a = np.array([list(map(int, input().split())) for _ in range(n)], dtype='u8')
res = np.eye(n, dtype='u8')
while k > 0:
    if k & 1:
        res = np.dot(res, a)
        res %= MOD
    a = np.dot(a, a)
    a %= MOD
    k >>= 1
ans = 0
for i in range(n):
    ans += res[i].sum()
print(int(ans) % MOD)

Submission status: Wrong Answer

Solution code:
import numpy as np


def pow(mat, k, mod):
    n = mat.shape[0]
    if k == 0:
        return np.eye(n, n, dtype=np.int64)
    if k % 2 == 0:
        sqrt_mat = pow(mat, k // 2, mod)
        return np.dot(sqrt_mat, sqrt_mat) % mod
    else:
        return np.dot(mat, pow(mat, k - 1, mod)) % mod


def main():
    MOD = 10 ** 9 + 7
    N, K = list(map(int, input().split(' ')))
    A = [list(map(int, input().split(' '))) for _ in range(N)]
    A = np.asarray(A, dtype=np.int64)
    D = pow(A, K, MOD)
    print(int(D.sum()) % MOD)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from numpy import array, eye

mod = 10 ** 9 + 7

N, K, *A = map(int, open(0).read().split())
A = array(A).reshape(N, N)

ans = eye(N, dtype=int)
while K:
    if K & 1:
        ans = (ans.dot(A)) % mod
    A = A.dot(A) % mod
    K //= 2

print(ans.sum() % mod)

Submission status: Wrong Answer

Solution code:
from numpy import int_, eye

mod = 10 ** 9 + 7

N, K, *A = map(int, open(0).read().split())
A = int_(A).reshape(N, N)

ans = eye(N, dtype=int_)
while K:
    if K & 1:
        ans = (ans.dot(A)) % mod
    A = A.dot(A) % mod
    K //= 2

print(ans.sum() % mod)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
read = sys.stdin.read
import numpy as np

MOD = 10**9+7
n, k, *A = map(int, read().split())
A = np.matrix(np.array(A, dtype=np.int64).reshape((n, n))) % MOD
def power(k):
  if k == 1:
    return A
  if k%2:
    return power(k-1) * A % MOD
  return power(k//2)**2 % MOD
ans = power(k).sum() % MOD
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np


def pow_matrix(mt, k, modp):
    ans = np.identity(mt.shape[0], dtype='uint64')
    while k:
        if k % 2:
            ans = ans.dot(mt)
            ans %= modp
        mt = mt.dot(mt)
        mt %= modp
        k //= 2
    return ans


def submit():
    n, k = map(int, input().split())
    a = [list(map(int, input().split())) for _ in range(n)]
    modp = 10 ** 9 + 7
    a = np.matrix(a, dtype='uint64')
    ak = pow_matrix(a, k, modp)
    print(int(np.sum(ak)) % modp)


submit()

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
input = sys.stdin.readline
mod = 10**9 + 7
n,k = map(int,input().split())
x = np.array([list(map(int,input().split())) for i in range(n)],dtype = np.int64)
# for i in ra
#  list(map(int,input().split())))
ans = np.eye(n,dtype = np.int64)
while k > 0:
    if k&1:
        ans = np.mod(np.dot(ans, x), mod)
        # ans = np.dot(ans, x)
    k = k >> 1
    x = np.mod(np.dot(x,x), mod)
    # x = np.dot(x,x)
res = 0
for i in range(n):
    for j in range(n):
        res += ans[i][j]
        res %= mod
print(res)

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
input = sys.stdin.readline
mod = 10**9 + 7
n,k = map(int,input().split())
x = np.array([list(map(int,input().split())) for i in range(n)],dtype = np.int64)
# for i in ra
#  list(map(int,input().split())))
ans = np.eye(n,dtype = np.int64)
while k > 0:
    if k&1:
        ans = np.mod(np.dot(ans, x), mod)
        # ans = np.dot(ans, x)
    k = k >> 1
    x = np.mod(np.dot(x,x), mod)
    # x = np.dot(x,x)
print(np.sum(ans)%mod)

Submission status: Wrong Answer

Solution code:
import numpy as np
mod = 10 ** 9 + 7


def matpow(A, x):
    if x == 1:
        return A % mod
    elif x % 2 == 0:
        return matpow(np.linalg.matrix_power(A, 2) % mod, x // 2)
    else:
        ans = matpow(np.linalg.matrix_power(A, 2) % mod, x // 2)
        ans = ans.dot(A) % mod
        return ans


N, K = map(int, input().split(" "))
A = []
for _ in range(N):
    A.append(list(map(int, input().split(" "))))

A = np.array(A, dtype=np.int64)
print(np.sum(matpow(A, K) % mod) % mod)

Submission status: Wrong Answer

Solution code:
import numpy as np
mod = 10 ** 9 + 7


def matpow(A, x):
    if x == 1:
        return A % mod
    elif x % 2 == 0:
        return matpow(np.linalg.matrix_power(A, 2) % mod, x // 2)
    else:
        ans = matpow(np.linalg.matrix_power(A, 2) % mod, x // 2)
        ans = ans.dot(A) % mod
        return ans


N, K = map(int, input().split(" "))
A = []
for _ in range(N):
    A.append(list(map(int, input().split(" "))))

A = np.array(A)
print(np.sum(matpow(A, K) % mod) % mod)

Submission status: Wrong Answer

Solution code:
import numpy as np
mod = 10 ** 9 + 7


def matpow(A, x):
    if x == 1:
        return A
    elif x % 2 == 0:
        return matpow(np.linalg.matrix_power(A, 2) % mod, x // 2)
    else:
        ans = matpow(np.linalg.matrix_power(A, 2) % mod, x // 2)
        ans = ans.dot(A)
        return ans % mod


N, K = map(int, input().split(" "))
A = []
for _ in range(N):
    A.append(list(map(int, input().split(" "))))

A = np.array(A)
print(np.sum(matpow(A, K) % mod) % mod)

Submission status: Wrong Answer

Solution code:
import numpy as np
mod=10**9+7
def solve():
    n,k = map(int,input().split())
    a = np.array([list(map(int,input().split())) for i in range(n)],dtype=np.int64)
    a=modpow(a,k)
    print(np.sum(a)%mod)
def modpow(A,k):
    n=len(A)
    res=np.eye(n,dtype=np.int64)
    for i in range(k.bit_length()):
        if k>>i&1:
            res=np.dot(res,A)
            for i in range(n):
                for j in range(n):
                    res[i][j]%=mod
        A=np.dot(A,A)
        for i in range(n):
            for j in range(n):
                A[i][j]%=mod
    return res
solve()

Submission status: Wrong Answer

Solution code:
import numpy as np

N, K = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(N)]
MOD = 10**9 + 7

a = np.matrix(a, np.int64)
ans = np.matrix(np.diag([1]*N), np.int64)

while K:
    K, m = divmod(K, 2)
    if m:
        ans = ans * a
        ans = np.mod(ans, MOD)
    a = a*a
    a = np.mod(a, MOD)

print(ans.sum() % MOD)

Submission status: Wrong Answer

Solution code:
import numpy as np

N, K = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(N)]
MOD = 10**9 + 7

a = np.matrix(a, np.int64)
ans = np.diag([1]*N)

while K:
    K, m = divmod(K, 2)
    if m:
        ans = ans * a
        ans = np.mod(ans, MOD)
    a = a*a
    a = np.mod(a, MOD)

print(ans.sum() % MOD)

Submission status: Wrong Answer

Solution code:
import numpy as np
n, k = [int(i) for i in input().split()]
mod = 10 ** 9 + 7
a = np.array([[int(i) for i in input().split()]
              for _ in range(n)], dtype=np.int64)
b = np.eye(n, dtype=np.int64)

while k != 0:
    if k & 1 == 1:
        b = np.dot(b, a)
        b %= mod
    a = np.dot(a, a) % mod
    k //= 2

c = np.dot(b, np.ones((n,), dtype=np.int64)) % mod
ans = 0

for i in c:
    ans += i
    ans %= mod

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
n, k = [int(i) for i in input().split()]
mod = 10 ** 9 + 7
a = np.array([[int(i) for i in input().split()]
              for _ in range(n)], dtype=np.int64)
b = np.eye(n, dtype=np.int64)

while k != 0:
    if k & 1 == 1:
        b = np.dot(b, a)
        b %= mod
    a = np.dot(a, a) % mod
    k //= 2

c = np.dot(np.ones((n,), dtype=np.int64), b) % mod
ans = 0

for i in c:
    ans += i
    ans %= mod

print(ans)

Submission status: Wrong Answer

Solution code:
from numpy import*
n,k,*a=int_(open(0).read().split())
a=matrix(a).reshape(n,n)
M=10**9+7
s=1
while k:s*=~k%2or a;s%=M;k//=2;a=a*a%M
print(sum(s)%M)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline
import numpy as np

def main():
    N,K = map(int,input().split())
    MOD = 10**9+7
    
    a = [list(map(int,input().split())) for _ in range(N)]
    arr = np.array(a,dtype=int)

    use = np.eye(N,dtype=int)
    while K>0:
        if K&1:
            use = np.dot(use,arr)%MOD
        arr = np.dot(arr,arr)%MOD
        K //= 2

    print(np.sum(use)%MOD)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline
import numpy as np

def main():
    N,K = map(int,input().split())
    MOD = 10**9+7
    
    a = np.array([list(map(int,input().split())) for _ in range(N)])
    arr = np.matrix(a)
    
    l = K.bit_length()
    use = np.matrix(np.eye(N),dtype=int)
    for i in range(l):
        if (K>>i)&1:
            use *= arr
            use %= MOD
        arr *= arr
        arr %= MOD

    print(np.sum(use)%MOD)

if __name__ == "__main__":
    main()