#include #include #include #include #include using namespace std; int pro[11], mat[5][5], row[5], col[5], res = 100000000, tmp, a[5][5]; int dia1, dia2; void setup() { int cnt = 0; tmp = 0, dia1 = 0, dia2 = 0; for(int i = 1; i <= 3; i++) { for(int j = 1; j <= 3; j++) mat[i][j] = pro[++cnt], tmp += abs(pro[cnt] - a[i][j]); row[i] = col[i] = 0; } } /* 1 5 9 2 6 7 3 4 8 */ 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() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ for(int i = 1; i <= 9; i++) pro[i] = i; for(int i = 1; i <= 3; i++) for(int j = 1; j <= 3; j++) cin >> a[i][j]; //1 5 9 2 6 7 3 4 8 /* permu[1] = 1; permu[2] = 5; permu[3] = 9; permu[4] = 2; permu[5] = 6; permu[6] = 7; permu[7] = 3; permu[8] = 4; permu[9] = 8; */ do { setup(); if(check()) res = min(res, tmp); } while(next_permutation(pro + 1, pro + 9 + 1)); cout << res; return 0; }