#include #define REP(i, a, n) for(ll i = ((ll) a); i < ((ll) n); i++) #define INF (1LL << 60) using namespace std; typedef long long ll; typedef vector vec; typedef vector mat; ll N, M; mat mul(mat &A, mat &B) { mat C(M, vector(M, -INF)); REP(i, 0, M) REP(j, 0, M) REP(k, 0, M) C[i][j] = max(C[i][j], A[i][k] + B[k][j]); return C; } mat pow(mat A, ll n) { mat B(M, vec(M, -INF)); REP(i, 0, M) B[i][i] = 1; while(n > 0) { if(n & 1) B = mul(B, A); A = mul(A, A); n >>= 1; } return B; } int main(void) { cin >> N >> M; mat A(N, vec(N, -INF)); REP(i, 0, M) REP(j, 0, M) cin >> A[j][i]; A = pow(A, N - 1); ll ans = 0; REP(i, 0, M) REP(j, 0, M) ans = max(ans, A[i][j]); cout << ans - 1 << endl; }