import sys input = sys.stdin.readline def bellmanford(s): N = (c+1)*m dist = [10**18]*N dist[s] = 0 for i in range(N-1): for s, t, w in edges: if dist[t]>dist[s]+w: dist[t] = dist[s]+w return min(dist) n = int(input())-1 m = int(input()) A = [list(map(int, input().split())) for _ in range(m)] dp = [[[0]*m for _ in range(m)] for _ in range(40)] for i in range(m): for j in range(m): dp[0][i][j] = A[i][j] for i in range(1, 40): for j in range(m): for k in range(m): for l in range(m): dp[i][j][k] = max(dp[i][j][k], dp[i-1][j][l]+dp[i-1][l][k]) edges = [] c = 0 for i in range(40): if (n>>i)&1: for j in range(m): for k in range(m): edges.append((c*m+j, (c+1)*m+k, -dp[i][j][k])) c += 1 wrong_answer = 0 for i in range(m): wrong_answer = max(wrong_answer, -bellmanford(i)) print(wrong_answer)