#include #include #include #include #include using namespace std; template void pm(const array &m) { for (int r=0; r void transpose(const array &g1, array &g2) { for (int r=0; r void rotate(const array &g1, array &g2) { for (int r=0; r array, 8> gen_magic() { array,8> g; for (auto &i:g[0]) { i=0; } // generate a magic matrix int r=0, c=n/2, v=1; do { g[0][r*n+c] = v; // update next row and column indices and matrix value v++; int newr = r-1, newc = c+1; if (newr<0) newr=n-1; if (newc>=n) newc=0; if (0!=g[0][newr*n+newc]) { r++; } else { r = newr; c = newc; } } while (0==g[0][r*n+c]); // rotate magic matrix x7 to generate all possible magic matrices transpose<3>(g[0], g[4]); // rotate g[0], 1..3 times) rotate<3>(g[0], g[1]); rotate<3>(g[1], g[2]); rotate<3>(g[2], g[3]); // rotate g[4], 1..3 times) rotate<3>(g[4], g[5]); rotate<3>(g[5], g[6]); rotate<3>(g[6], g[7]); #if 0 pm<3,3>(g[0]); printf("\n"); pm<3,3>(g[1]); printf("\n"); pm<3,3>(g[2]); printf("\n"); pm<3,3>(g[3]); printf("\n"); pm<3,3>(g[4]); printf("\n"); pm<3,3>(g[5]); printf("\n"); pm<3,3>(g[6]); printf("\n"); pm<3,3>(g[7]); printf("\n"); #endif return g; } template int cost(const array &m1, const array &m2) { int tc=0; for (int i=0; i int min_cost(const array, 8> &g, const array &m) { int mc = -1; for (const auto &ms:g) { int c = cost<3>(ms, m); if (-1==mc || c m; for (int i=0; i<9; i++) { scanf("%d", &m[i]); } printf("%d\n", min_cost<3>(gen_magic<3>(), m)); return 0; }