#include #define rep(i,a,b) for(int i=a;i=b;i--) #define fore(i,a) for(auto &i:a) #pragma GCC optimize ("-O3") using namespace std; void _main(); int main() { cin.tie(0); ios::sync_with_stdio(false); _main(); } //--------------------------------------------------------------------------------------------------- /*---------------------------------------------------------------------------------------------------             ∧_∧       ∧_∧  (´<_` )  Welcome to My Coding Space!      ( ´_ゝ`) /  ⌒i     /   \    | |     /   / ̄ ̄ ̄ ̄/  |   __(__ニつ/  _/ .| .|____      \/____/ (u ⊃ ---------------------------------------------------------------------------------------------------*/ typedef long long ll; ll N; int M; // dp[len][s][t] := max ll dp[1010][30][30]; ll A[30][30]; //--------------------------------------------------------------------------------------------------- void _main() { cin >> N >> M; rep(y, 0, M) rep(x, 0, M) cin >> A[y][x]; rep(s, 0, M) rep(t, 0, M) dp[2][s][t] = A[s][t]; rep(le, 2, 1000) rep(s, 0, M) rep(t, 0, M) { rep(to, 0, M) dp[le + 1][s][to] = max(dp[le + 1][s][to], dp[le][s][t] + A[t][to]); } ll ans = 0; if (N <= 100) { rep(s, 0, M) rep(t, 0, M) ans = max(ans, dp[N][s][t]); } else { rep(s, 0, M) rep(c, 0, M) rep(t, 0, M) rep(len1, 1, 31) rep(len2, 3, 31) rep(len3, 1, 31) { if (len1 == 1 && s != c) continue; if (len3 == 1 && c != t) continue; ll d = N - len1 - len3 + 1; if (d % (len2 - 1) == 0) { ll cc = dp[len1][s][c] + dp[len3][c][t]; cc += dp[len2][c][c] * (d / (len2 - 1)); if (ans < cc) { ans = cc; } } } } cout << ans << endl; return; string st = "ABCDEFGHIJKL"; int ss = 0, tt = 0; rep(s, 0, M) rep(t, 0, M) if (ans == dp[N][s][t]) { ss = s; tt = t; } string res = ""; res += st[tt]; while (N) { rep(t, 0, M) if (dp[N][ss][tt] == dp[N - 1][ss][t] + A[t][tt]) { res = st[t] + res; tt = t; N--; break; } } cout << res << endl; }