#include #include #include #include #include #include #include #include #include using namespace std; int costFunc(int x, int y) { return abs(x - y); } const int needSum = 15; int main() { int s[9]; for (int i = 0; i < 9; ++i) cin >> s[i]; int magic[9]; //= {4, 9, 2, 3, 5, 7,8, 1, 6}; iota(magic, magic + 9, 1); int bestans = 100000; array checkMagic; do { int curans = inner_product(magic, magic + 9, s, 0, plus(), costFunc); if (curans >= bestans) continue; checkMagic.fill(0); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { int cMagic = magic[3*i + j]; checkMagic[i] += cMagic; checkMagic[3 + j] += cMagic; if (i == j) checkMagic[6] += cMagic; if (j + i == 2) checkMagic[7] += cMagic; } } if (all_of(checkMagic.begin(), checkMagic.end(), [](int x){ return x == needSum; })) bestans = curans; } while (next_permutation(magic, magic + 9)); cout << bestans << endl; return 0; }