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: Time Limit Exceeded

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

MOD = 10**9+7

def dot(A, B):
    N = len(A)
    K = len(A[0])
    assert len(B) == K
    M = len(B[0])
    C = [[0] * M for _ in range(N)]
    for i in range(N):
        for j in range(M):
            for k in range(K):
                C[i][j] += (A[i][k] * B[k][j]) % MOD
                C[i][j] % + MOD
    return C



def mp(A, n):
    assert len(A) == len(A[0])
    B = [[0] * len(A) for _ in range(len(A))]
    for i in range(len(A)):
        B[i][i] = 1

    while n:
        n, i = divmod(n, 2)
        if i:
            B = dot(A, B)
        A = dot(A, A)

    return B


ans = sum([sum(r) % MOD for r in mp(A, K)]) % MOD
print(ans)

Submission status: Time Limit Exceeded

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

MOD = 10**9+7

def dot(A, B):
    N = len(A)
    K = len(A[0])
    assert len(B) == K
    M = len(B[0])
    C = [[0] * M for _ in range(N)]
    for i in range(N):
        for j in range(M):
            for k in range(K):
                C[i][j] += A[i][k] * B[k][j]
            C[i][j] %= MOD
    return C



def mp(A, n):
    assert len(A) == len(A[0])
    B = [[0] * len(A) for _ in range(len(A))]
    for i in range(len(A)):
        B[i][i] = 1

    while n:
        n, i = divmod(n, 2)
        if i:
            B = dot(A, B)
        A = dot(A, A)

    return B


ans = sum([sum(r) % MOD for r in mp(A, K)]) % MOD
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
import numpy 
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
#mint
class ModInt:
    def __init__(self, x):
        self.x = x % mod
    
    def __str__(self):
        return str(self.x)
    
    __repr__ = __str__

    def __add__(self, other):
        if isinstance(other, ModInt):
            return ModInt(self.x + other.x)
        else:
            return ModInt(self.x + other)

    __radd__ = __add__
        
    def __sub__(self, other):
        if isinstance(other, ModInt):
            return ModInt(self.x - other.x)
        else:
            return ModInt(self.x - other)

    def __rsub__(self, other):
        if isinstance(other, ModInt):
            return ModInt(other.x - self.x)
        else:
            return ModInt(other - self.x)

    def __mul__(self, other):
        if isinstance(other, ModInt):
            return ModInt(self.x * other.x)
        else:
            return ModInt(self.x * other)

    __rmul__ = __mul__

    def __truediv__(self, other):
        if isinstance(other, ModInt):
            return ModInt(self.x * pow(other.x, mod-2,mod))
        else:
            return ModInt(self.x * pow(other, mod - 2, mod))
            
    def __rtruediv(self, other):
        if isinstance(other, self):
            return ModInt(other * pow(self.x, mod - 2, mod))
        else:
            return ModInt(other.x * pow(self.x, mod - 2, mod))
            

    def __pow__(self, other):
        if isinstance(other, ModInt):
            return ModInt(pow(self.x, other.x, mod))
        else:
            return ModInt(pow(self.x, other, mod))
            

    def __rpow__(self, other):
        if isinstance(other, ModInt):
            return ModInt(pow(other.x, self.x, mod))
        else:
            return ModInt(pow(other, self.x, mod))

def main():
    N,K=MI()
    A=LLIN(N)
    
    B=[[ModInt(0)]*N for _ in range(N)]
    for a,vec in enumerate(A):
        for b,boo in enumerate(vec):
            if(boo):
                B[a][b] = 1
    C=numpy.matrix(B)
    ans_mat = C**K

    ans = ModInt(0)
    for i in range(N):
        for j in range(N):
            ans += ans_mat[i,j]
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
import numpy 
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
#mint
class ModInt:
    def __init__(self, x):
        self.x = x % mod
    
    def __str__(self):
        return str(self.x)
    
    __repr__ = __str__

    def __add__(self, other):
        if isinstance(other, ModInt):
            return ModInt(self.x + other.x)
        else:
            return ModInt(self.x + other)

    __radd__ = __add__
        
    def __sub__(self, other):
        if isinstance(other, ModInt):
            return ModInt(self.x - other.x)
        else:
            return ModInt(self.x - other)

    def __rsub__(self, other):
        if isinstance(other, ModInt):
            return ModInt(other.x - self.x)
        else:
            return ModInt(other - self.x)

    def __mul__(self, other):
        if isinstance(other, ModInt):
            return ModInt(self.x * other.x)
        else:
            return ModInt(self.x * other)

    __rmul__ = __mul__

    def __truediv__(self, other):
        if isinstance(other, ModInt):
            return ModInt(self.x * pow(other.x, mod-2,mod))
        else:
            return ModInt(self.x * pow(other, mod - 2, mod))
            
    def __rtruediv(self, other):
        if isinstance(other, self):
            return ModInt(other * pow(self.x, mod - 2, mod))
        else:
            return ModInt(other.x * pow(self.x, mod - 2, mod))
            

    def __pow__(self, other):
        if isinstance(other, ModInt):
            return ModInt(pow(self.x, other.x, mod))
        else:
            return ModInt(pow(self.x, other, mod))
            

    def __rpow__(self, other):
        if isinstance(other, ModInt):
            return ModInt(pow(other.x, self.x, mod))
        else:
            return ModInt(pow(other, self.x, mod))

def main():
    N,K=MI()
    A=LLIN(N)
    
    B=[[ModInt(0)]*N for _ in range(N)]
    for a,vec in enumerate(A):
        for b,boo in enumerate(vec):
            if(boo):
                B[a][b] = 1
    C=numpy.matrix(B)
    ans_mat = C**K

    ans = ModInt(0)
    for i in range(N):
        for j in range(N):
            ans += ans_mat[i,j]
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
mod = 10**9+7
A = [list(map(int, input().split())) for _ in range(n)]

# A*B
def mul(a, b):
    c = [[0]*len(b[0]) for i in range(len(a))]
    for i in range(len(a)):
        for k in range(len(b)):
            for j in range(len(b[0])):
                c[i][j] = (c[i][j] + a[i][k]*b[k][j])%mod

    return c

#A**n
def pow(a, n):
    b = [[0]*len(a) for i in range(len(a))]
    for i in range(len(a)):
        b[i][i] = 1
    while n > 0:
        if n & 1 == 1:
            b = mul(a, b)
        a = mul(a, a)
        n = n>>1
    return b

B = pow(A, k)
#print(B)
ans = 0
for i in range(n):
    ans += sum(B[i])
    ans %= mod
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1
sys.setrecursionlimit(10**7)

n,k = map(int,input().split())
A = [list(map(int,input().split())) for i in range(n)]
def calc(A,B):
  res = [[0]*n for i in range(n)]
  for i in range(n):
    for j in range(n):
      for k in range(n):
        res[i][j] += A[i][k] * B[k][j]
      res[i][j] %= mod
  return res


def power(A,k):
  if k == 1:
    return A
  elif k % 2 == 0:
    tmp = power(A,k//2)
    return calc(tmp,tmp)
  elif k % 2 == 1:
    return calc(A,power(A,k-1))

result = power(A,k)
print(sum(map(sum,result))%mod)

Submission status: Time Limit Exceeded

Solution code:
mod = 10**9+7


def mat_mul(A, B):
    # A,Bは正方行列とする
    C = [[0]*N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            C[i][j] = sum(A[i][k] * B[k][j] for k in range(N)) % mod
    return C


def matpow(A, n):
    B = [[0]*N for _ in range(N)]
    for i in range(N):
        B[i][i] = 1
    while n > 0:
        if n & 1:
            B = mat_mul(A, B)
        A = mat_mul(A, A)
        n //= 2
    return B


if __name__ == "__main__":
    N, K = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(N)]
    A = matpow(A, K)
    ans = 0
    for a in A:
        ans = (ans + sum(a)) % mod
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
A = [list(map(int, input().split())) for i in range(N)]
MOD = 10**9 + 7


def dot(M1, M2, mod=10**9+7):
  n = len(M1)
  res = [[0]*n for _ in range(n)]
  for i in range(n):
    for j in range(n):
      for k in range(n):
        res[i][j] += M1[i][k] * M2[k][j] % MOD
  
  return res


def power(M, k, mod=10**9+7):
  if k == 1:
    return M
  elif k%2 == 0:
    return power(dot(M, M, mod), k//2)
  else:
    return dot(M, power(dot(M, M, mod), k//2), mod)


trans = power(A, K) 

ans = 0
for t in trans:
  ans += sum(t)%MOD
  ans %= MOD

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from numpy import*
N,K,*A=map(int,open(0).read().split())
X=matrix(A,"O").reshape(N,N)
M=10**9+7
S=1
while K:S*=~K%2or X;K//=2;X*=X%M
print(sum(S)%M)

Submission status: Time Limit Exceeded

Solution code:
def mmult(A, B):
    global mod
    n, m, l = len(A), len(B), len(B[0])
    ret = [[0]*l for _ in range(n)]
    for i in range(n):
        for j in range(m):
            for k in range(l):
                ret[i][k] = (ret[i][k]+A[i][j]*B[j][k])%mod
    return ret
def mpow(A, n):
    if n == 0: return [[1 if i==j else 0 for j in range(len(A))] for i in range(len(A))]
    if n % 2: return mmult(mpow(A, n-1), A)
    return mpow(mmult(A, A), n//2)

mod = 10**9+7
N, K = map(int, input().split())
X = [[int(a) for a in input().split()] for _ in range(N)]
print(sum([sum(x) for x in mpow(X, K)]) % mod)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

def main():
    MOD = int(1e9 + 7)

    n, k = map(int, input().split())
    can = np.zeros((n,n), dtype=object)
    for i in range(n):
        for j, e in enumerate(int(c) for c in input().split()):
            can[i,j] = e

    answer = np.identity(n, dtype=object)
    while k:
        if k % 2:
            answer = np.dot(answer, can)
        can = np.dot(can, can)
        k //= 2

    total = 0
    for i in range(n):
        for j in range(n):
            total += answer[i,j]
            if total >= MOD:
                total -= MOD

    print(total)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

def main():
    MOD = int(1e9 + 7)

    n, k = map(int, input().split())
    can = np.zeros((n,n), dtype=object)
    for i in range(n):
        for j, e in enumerate(int(c) for c in input().split()):
            can[i,j] = e

    answer = np.identity(n, dtype=object)
    while k:
        if k % 2:
            answer = np.dot(answer, can)
        can = np.dot(can, can)
        k //= 2

    total = 0
    for i in range(n):
        for j in range(n):
            total += int(answer[i,j])
            if total >= MOD:
                total -= MOD

    print(total)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

N, K = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(N)]
A = np.array(A, dtype=object)

ans = np.linalg.matrix_power(A, K).sum()
ans %= mod
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
p = 10**9+7
def pow(X,k):
    if k==0:
        return np.eye(X.shape[0])
    if k==1:
        return X
    if k%2==0:
        return np.dot(pow(X,k//2),pow(X,k//2))%p
    else:
        return np.dot(X,np.dot(pow(X,(k-1)//2),pow(X,(k-1)//2))%p)%p
N,K = map(int,input().split())
A = np.zeros((N,N))
for i in range(N):
    a = np.array(list(map(int,input().split())))
    A[i][:] = a[:]
X = pow(A,K)
cnt = 0
for i in range(N):
    for j in range(N):
        cnt = (cnt+X[i][j])%p
print(int(cnt))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

def mat_dot(A, B):
    """ 行列の積 """

    # 1次元リストが来たら2次元の行列にする
    if not isinstance(A[0], list) and not isinstance(A[0], tuple):
        A = [A]
    if not isinstance(B[0], list) and not isinstance(A[0], tuple):
        B = [[b] for b in B]
    n1 = len(A)
    n2 = len(A[0])
    _ = len(B)
    m2 = len(B[0])
    res=list2d(n1, m2, 0)
    for i in range(n1):
        for j in range(m2):
            for k in range(n2):
                res[i][j] += A[i][k] * B[k][j]
                res[i][j] %= MOD
    return res

def mat_pow(mat, n, k):
    """ n*nの行列matを行列累乗でk乗する """

    res = list2d(n, n, 0)
    for i in range(n):
        res[i][i] = 1
    # 繰り返し二乗法
    while k > 0:
        if k & 1:
            res = mat_dot(res, mat)
        mat = mat_dot(mat, mat)
        k >>= 1
    return res

N, K = MAP()
G = [None] * N
for i in range(N):
    G[i] = LIST()

# 行列累乗でK項先へ
mat = mat_pow(G, N, K)

# グラフを行列としてK乗すれば、長さKのパスの総数が分かる(mat[i][j]=1で頂点i〜jが長さKのパスで繋がってる)
print(sum([sum(row)%MOD for row in mat])%MOD)

Submission status: Time Limit Exceeded

Solution code:
MOD = 10**9 + 7

def mul(a, b):
    return [
        [sum(aij * bij for aij, bij in zip(ai, bi)) % MOD for bi in zip(*b)]
        for ai in a]

def pow(b, k):
    if k == 1:
        return b
    i = 0
    while 2 ** (i + 1)<= k:
        i += 1

    k -= 2 ** i
    if k > 0:
        t = pow(b, k)
    for j in range(i):
        b = mul(b, b)
    if k > 0:
        b = mul(b, t)
    return b


def main():
    N, K = (int(i) for i in input().split())
    A = []
    for i in range(N):
        A.append([int(j) for j in input().split()])
    A = [i for i in zip(*A)]
    v = [[1] * N]
    return sum(mul(v, pow(A, K))[0]) % MOD

print(main())

Submission status: Time Limit Exceeded

Solution code:
mod = 10**9 + 7

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

def dot(X, Y):
    x = len(X)
    y = len(Y[0])
    z = len(Y)
    C = [[0] * y for _ in range(x)]
    for i in range(x):
        for j in range(y):
            for k in range(z):
                C[i][j] += X[i][k] * Y[k][j]
                C[i][j] %= mod
    return C

B = [[0] * N for _ in range(N)]
for k in range(N):
    B[k][k] = 1

while K > 0:
    if K & 1:
        B = dot(B, A)
    A = dot(A, A)
    K >>= 1

ans = 0
for i in range(N):
    for j in range(N):
        ans += B[i][j]
        ans %= mod

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)
def input():
    return sys.stdin.readline()[:-1]
from collections import *
import math
from bisect import *
import functools
INF = float('inf')
mod = 10**9+7

def mat(A, B):
    n = len(A)
    C = [[0] * n for i in range(n)]
    for i in range(n):
        for j in range(n):
            for k in range(n):
                C[i][j] += A[i][k]*B[k][j]
            C[i][j] %= mod
    return C

N, K = map(int, input().split())
a = [[int(x) for x in input().split()] for i in range(N)]
b = [[0] * N for i in range(N)]
for i in range(N):
    b[i][i] = 1
while K > 0:
    if K % 2:
        b = mat(b, a)
    a = mat(a, a)
    K //= 2
print(sum([sum(_b) for _b in b])%mod)

Submission status: Time Limit Exceeded

Solution code:
# @author 

import sys

class RWalk:
    def solve(self):

        MOD = 10 ** 9 + 7

        def mult(A, B):
            n, m, p = len(A), len(A[0]), len(B[0])
            assert(len(B) == m)
            C = [[0] * p for _ in range(n)]
            for i in range(n):
                for j in range(p):
                    for k in range(m):
                        C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD

            return C

        def pow(A, k):
            n, m = len(A), len(A[0])
            if k == 0:
                return [[1 if i == j else 0 for j in range(m)] for i in range(n)]

            if k % 2 == 0:
                return pow(mult(A, A), k // 2)

            return mult(A, pow(A, k - 1))


        n, k = [int(_) for _ in input().split()]
        a = []
        for i in range(n):
            a.append([int(_) for _ in input().split()])

        print(sum([sum(line) for line in pow(a, k)]) % MOD)

solver = RWalk()
input = sys.stdin.readline

solver.solve()

Submission status: Time Limit Exceeded

Solution code:
MOD = 10**9+7

def mat_dot(one, two, mod):
	return [[sum([(one[i][k]*two[k][j])%mod for k in range(max(len(two), len(one[0])))])%mod for j in range(len(two[0]))] for i in range(len(one))]

def mat_pow(mat, exp, mod):
	size = len(mat)
	res = [[0 for _ in range(size)] for _ in range(size)]
	for i in range(size):
		res[i][i] = 1
	cnt = 0
	while (1<<cnt) <= exp:
		if (exp>>cnt)&1:
			res = mat_dot(res, mat, mod)
		mat = mat_dot(mat, mat, mod)
		cnt += 1
	return res

n, k = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
b = mat_pow(a, k, MOD)
print(sum([sum(x) for x in b]) % MOD)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

N, K = map(int, sys.stdin.readline().split())

dp = np.zeros((N,N), dtype='int64')

for i in range(N):
    dp[i] = np.array(list(map(int, sys.stdin.readline().split())))
    
n = dp.copy()
for i in range(K-1):
    dp = np.dot(dp, n)
    
print(sum(sum(dp)) % (1000000000 + 7))

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

N, K = map(int, sys.stdin.readline().split())

dp = np.zeros((N,N), dtype='int64')

for i in range(N):
    dp[i] = np.array(list(map(int, sys.stdin.readline().split())))
    
n = dp.copy()
for i in range(K-1):
    dp = np.dot(dp, n)
    
print(sum(sum(dp)))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
N,K=list(map(int,input().strip().split(' ')))
A=[]
for _ in range(N):
    A+=[list(map(int,input().strip().split(' ')))]
dic={}
MOD=10**9+7
def findout(i,j,k):
    
    if k==1:
        if A[i][j]==1:
            return 1
        else:
            return 0
    if (i,j,k) in dic:
        return dic[(i,j,k)]
    N=len(A)
    a1=k//2
    a2=k-a1
    
    ans=0
    for node in range(N):
        ans+=(findout(i,node,a1)*findout(node,j,a2))%MOD
    dic[(i,j,k)]=ans
    return ans
ans=0
for i in range(N):
    for j in range(N):
        ans+=findout(i,j,K)
        ans%=MOD
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(input())
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())

N,K = inpl()
aa = [inpl() for _ in range(N)]

def Matdot(A,B):
    C = [[0]*N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            for k in range(N):
                C[i][j] += A[i][k]*B[k][j]
            C[i][j] %= mod
    return C

def power(aa,k):
    if k == 1:
        return aa
    elif k%2 == 0:
        tmp = power(aa,k//2)
        return Matdot(tmp,tmp)
    else:
        tmp = power(aa,(k-1)//2)
        return Matdot(Matdot(tmp,tmp),aa)


aa =  power(aa,K)
ans = 0
for a in aa:
    ans += sum(a)
    ans %= mod
print(ans)

Submission status: Time Limit Exceeded

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

MOD=10**9+7
N, K = map(int, input().split())
grid = np.empty((0,N), int)
for i in range(N):
  array = list(map(int, input().strip().split()))
  array2 = np.array(array)
  grid = np.append(grid,[array2],axis=0)
#print(grid)
dp=[[grid]]
gridsave=grid
i=1
while 2**i<=K:
  #print(i)
  #dp.insert(1,grid*grid)
  #gridsave=np.dot(dp[i-1][0],dp[i-1][0])
  gridsave=[[0]*N]*N
  gridsave =np.array(gridsave)
  for j in range(N):
    for k in range(N):
      for l in range(N):
        #print(l,'1 ',dp[i-1][0][j][l])
        #print(l,'2 ',dp[i-1][0][l][k])
        gridsave[j][k]=(gridsave[j][k]+(dp[i-1][0][j][l]*dp[i-1][0][l][k])%MOD)%MOD

  gridsave=np.mod(gridsave,MOD)
  #print(gridsave)
  dp.append([gridsave])
  i+=1
i-=1
K-=2**i
i-=1
#print('dp',dp)
grid1=dp[len(dp)-1][0]
#print(grid1)
#print(i)
while K>0:
  if K>=2**i:
    #print('i',i)
    grid1=np.dot(grid1,dp[i][0])
    grid1=np.mod(grid1,MOD)
    K-=2**i
    #print('grid1',grid1)
  i-=1
  #print('K',K)
ans=0
#print(grid1)
for i in range(N):
  for j in range(N):
    ans=(ans+grid1[i][j])%MOD
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
dp = [list(map(int, input().split())) for i in range(n)]
MOD = 10**9 + 7

def _mul(A, B, MOD):
    C = [[0] * len(B[0]) for i in range(len(A))]
    for i in range(len(A)):
        for k in range(len(B)):
            for j in range(len(B[0])):
                C[i][j] = (C[i][j] + A[i][k]*B[k][j]) % MOD
    return C

#A**n
def pow(A, n, MOD):
    B = [[0] * len(A) for i in range(len(A))]
    for i in range(len(A)):
        B[i][i] = 1
    while n > 0:
        if n & 1:
            B = _mul(A, B, MOD)
        A = _mul(A, A, MOD)
        n  = n // 2
    return B

ans_matrix = pow(dp, k, MOD)
ans = 0
for i in range(n):
    ans += sum(ans_matrix[i])
    ans %= MOD
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline


def dot(a, b):
    c = [[0] * n for _ in range(n)]
    for i, ai in enumerate(a):
        for j, bj in enumerate(zip(*b)):
            ck = 0
            for ak, bk in zip(ai, bj):
                ck += ak * bk
                c[i][j] = ck % md
    return c


def pwr(a, k):
    c = None
    while c == None:
        if k & 1:
            c = a
        a = dot(a, a)
        k >>= 1

    while k > 0:
        if k & 1:
            c = dot(a, c)
        a = dot(a, a)
        k >>= 1
    return c


md = 10 ** 9 + 7
n, k = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
print(sum([sum(pk) % md for pk in pwr(a, k)]) % md)

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline


def dot(a, b):
    c = [[0] * n for _ in range(n)]
    for i in range(n):
        ai = a[i]
        for j in range(n):
            ck = 0
            for ak, bk in zip(ai, [bi[j] for bi in b]):
                ck += ak * bk
                c[i][j] = ck % md
    return c


def pwr(a, k):
    c = None
    while c == None:
        if k & 1:
            c = a
        a = dot(a, a)
        k >>= 1

    while k > 0:
        if k & 1:
            c = dot(a, c)
        a = dot(a, a)
        k >>= 1
    return c


md = 10 ** 9 + 7
n, k = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
print(sum([sum(pk) % md for pk in pwr(a, k)]) % md)

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline


def dot(a, b):
    an = len(a)
    bn = len(b[0])
    c = [[0] * bn for _ in range(an)]
    for i in range(an):
        ai = a[i]
        for j in range(bn):
            ck = 0
            for ak, bk in zip(ai, [bi[j] for bi in b]):
                ck += ak * bk
                c[i][j] = ck % md
    return c


def pwr(a, k):
    c = None
    while c == None:
        if k & 1:
            c = a
        a = dot(a, a)
        k >>= 1

    while k > 0:
        if k & 1:
            c = dot(a, c)
        a = dot(a, a)
        k >>= 1
    return c


md = 10 ** 9 + 7
n, k = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
e = [[1] * n]
print(sum(dot(e, pwr(a, k))[0]) % md)

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline


def dot(a, b):
    an = len(a)
    bn = len(b[0])
    c = [[0] * bn for _ in range(an)]
    for i in range(an):
        ai = a[i]
        for j in range(bn):
            ck = 0
            for ak, bk in zip(ai, [bi[j] for bi in b]):
                ck += (ak * bk)
                c[i][j] = ck % md
    return c


def pwr(a, k):
    c = None
    while k > 0:
        if k & 1:
            if c:
                c = dot(a, c)
            else:
                c = a
        a = dot(a, a)
        k >>= 1
    return c


md = 10 ** 9 + 7
n, k = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
print(sum([sum(pk) % md for pk in pwr(a, k)]) % md)

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline


def dot(a, b):
    an = len(a)
    bn = len(b[0])
    c = [[0] * bn for _ in range(an)]
    for i in range(an):
        ai = a[i]
        for j in range(bn):
            ck = 0
            for ak, bk in zip(ai, [bi[j] for bi in b]):
                ck += (ak * bk) % md
                c[i][j] = ck % md
    return c


def pwr(a, k):
    c = None
    while k > 0:
        if k & 1:
            if c:
                c = dot(a, c)
            else:
                c = a
        a = dot(a, a)
        k >>= 1
    return c


md = 10 ** 9 + 7
n, k = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
print(sum([sum(pk) % md for pk in pwr(a, k)]) % md)

Submission status: Time Limit Exceeded

Solution code:
def dot(a, b):
    an = len(a)
    bn = len(b[0])
    c = [[0] * bn for _ in range(an)]
    for i in range(an):
        ai = a[i]
        for j in range(bn):
            ck = 0
            for ak, bk in zip(ai, [bi[j] for bi in b]):
                ck += ak * bk
                c[i][j] = ck % md
    return c


def pwr(a, k):
    c = None
    while k > 0:
        if k & 1:
            if c:
                c = dot(a, c)
            else:
                c = a
        a = dot(a, a)
        k >>= 1
    return c


md = 10 ** 9 + 7
n, k = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
print(sum([sum(pk) % md for pk in pwr(a, k)]) % md)

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline

md = 10 ** 9 + 7
n, k = map(int, input().split())
n1 = n + 1
dp = [0]
ko = [[]]
for _ in range(n):
    s = input()
    st = 0
    kk = []
    while 1:
        i = s.find("1", st)
        if i == -1: break
        kk += [i // 2 + 1]
        st = i + 1
    ko += [kk]
    dp += [len(kk)]

for _ in range(k - 1):
    ndp = [0] * n1
    for i in range(1, n1):
        for ki in ko[i]:
            ndp[i] += dp[ki]
            ndp[i] %= md
    dp = ndp

print(sum(dp) % md)