#include #include #include #include #include using namespace std; int permutation[11], mat[5][5], row[5], col[5], res = 100000000, gg, ori[5][5]; int dia1, dia2; void setup() { int cnt = 0; gg = 0, dia1 = 0, dia2 = 0; for(int i = 1; i <= 3; i++) { for(int j = 1; j <= 3; j++) mat[i][j] = permutation[++cnt], gg += abs(permutation[cnt] - ori[i][j]); row[i] = col[i] = 0; } } bool check() { for(int i = 1; i <= 3; i++) { for(int j = 1; j <= 3; j++) { row[i] += mat[i][j]; col[j] += mat[i][j]; if(i == j) dia1 += mat[i][j]; if(i == 3 - j + 1) dia2 += mat[i][j]; } } return row[1] == row[2] && row[1] == row[3] && row[1] == col[1] && col[1] == col[2] && col[2] == col[3] && col[3] == dia1 && dia1 == dia2; } int main() { for(int i = 1; i <= 9; i++) permutation[i] = i; for(int i = 1; i <= 3; i++) for(int j = 1; j <= 3; j++) cin >> ori[i][j]; do { setup(); if(check()) { res = min(res, gg); } } while(next_permutation(permutation + 1, permutation + 9 + 1)); cout << res; return 0; }