#include #include #include #include #include using namespace std; vector rotate(vector source) { vector new_vector(9); new_vector[0] = source[2]; new_vector[1] = source[5]; new_vector[2] = source[8]; new_vector[3] = source[1]; new_vector[4] = source[4]; new_vector[5] = source[7]; new_vector[6] = source[0]; new_vector[7] = source[3]; new_vector[8] = source[6]; return new_vector; } vector reflect_horizontally(vector source) { iter_swap(source.begin(), source.begin() + 2); iter_swap(source.begin() + 3, source.begin() + 5); iter_swap(source.begin() + 6, source.begin() + 8); return source; } vector reflect_vertically(vector source) { iter_swap(source.begin(), source.begin() + 6); iter_swap(source.begin() + 1, source.begin() + 7); iter_swap(source.begin() + 2, source.begin() + 8); return source; } void derive_squares(vector> &results, vector input) { // For each of the four rotations, add the square, and its two reflections. for (int i = 0; i < 4; i++) { input = rotate(input); results.push_back(input); results.push_back(reflect_horizontally(input)); results.push_back(reflect_vertically(input)); } } int distance(vector &a, vector &b) { int total = 0; for (int i = 0; i < a.size(); i++) { total += abs(a[i] - b[i]); } return total; } int minimum_distance(vector> &squares, vector input) { int best_so_far = 100000; for (vector square : squares) { int current_distance = distance(square, input); if (current_distance < best_so_far) { best_so_far = current_distance; } } return best_so_far; } int main() { // There are only 12 natural magic squares of order 3. // Start by deriving them. // Note that we use a flat representation. vector base_square = {2, 7, 6, 9, 5, 1, 4, 3, 8}; vector> squares; derive_squares(squares, base_square); int integer; vector square; for (int i = 0; i < 9; i++) { cin >> integer; square.push_back(integer); } cout << minimum_distance(squares, square) << '\n'; return 0; }