#include #include #include #include #include using namespace std; int main() { vector matrix(9); int cost = 0; for (int i = 0; i < 9; i++) { cin >> matrix[i]; } // center tile is always 5 if (matrix[4] != 5) { cost += abs(matrix[4]-5); } matrix.erase(matrix.begin()+4); vector tempMatrix(matrix); matrix[3] = tempMatrix[4]; matrix[4] = tempMatrix[7]; matrix[5] = tempMatrix[6]; matrix[6] = tempMatrix[5]; matrix[7] = tempMatrix[3]; // now look for ways to produce 27618349 or 43816729 sequence (cw or ccw) int seq1[] = {2,7,6,1,8,3,4,9}; int seq2[] = {4,3,8,1,6,7,2,9}; int lowestCost = 100; for (int i = 0; i < 4; i++) { int thisCost1 = 0, thisCost2 = 0; for (int j = 0; j < 8; j++) { thisCost1 += abs(matrix[(j+2*i)%8] - seq1[j]); thisCost2 += abs(matrix[(j+2*i)%8] - seq2[j]); } int thisCost = min(thisCost1, thisCost2); lowestCost = min(lowestCost, thisCost); } cost += lowestCost; cout << cost << endl; return 0; }