#include #include #include #define NUM 3 #define SQUARE NUM*NUM #define SUM 8 using namespace std; /* /* Returns '1' if the square is 'magical' and 0 otherwise */ int isMagic(int* matrix) { int i, j, k = 0, sum_f, sum[SUM] = {0}; for(i = 0; i < SQUARE; i+=3) { for(j = 0; j < NUM; j++) sum[k] += matrix[i+j]; k++; } for(i = 0; i < NUM; i++) { for(j = 0; j < SQUARE; j+=3) sum[k] += matrix[i+j]; k++; } for(i = 0; i < SQUARE; i+=(NUM+1)) sum[k] += matrix[i]; k++; for(i = NUM-1; i < SQUARE-1; i+=(NUM-1)) sum[k] += matrix[i]; sum_f = sum[0]; for(i = 0; i < SUM; i++) { if(sum[i] != sum_f) return 0; } return 1; } int main() { int i, sol = 1000; int input[SQUARE] = {0}; int matrix[SQUARE] = {0}; for(i = 0; i < SQUARE; i++) matrix[i] = i+1; for(i = 0; i < SQUARE; i++) scanf("%d", &input[i]); do { if(isMagic(matrix)) { int sum = 0; for(i = 0; i < SQUARE; i++) sum += abs(matrix[i]-input[i]); sol = min(sol, sum); } } while(next_permutation(matrix, matrix+SQUARE)); printf("%d\n", sol); return 0; }