/** * author: ivanzuki * created: Thu May 27 2021 **/ #include using namespace std; string to_string(string s) { return '"' + s + '"'; } string to_string(const char* s) { return to_string((string) s); } string to_string(bool b) { return (b ? "true" : "false"); } template string to_string(pair p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } template string to_string(A v) { bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res; } void debug_out() { cerr << endl; } template void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } template void dout(string name, int idx, T arg) { cerr << name << " = " << to_string(arg); } template void dout(string names, int idx, T1 arg, T2... args) { cerr << names.substr(0, names.find(',')) << " = " << to_string(arg) << ", "; dout(names.substr(names.find(',') + 2), idx + 1, args...); } #ifdef LOCAL #define debug(...) cerr << "[", dout(#__VA_ARGS__, 0, __VA_ARGS__), cerr << "]" << endl; #else #define debug(...) 42 #endif class dsu { public: vector p; int n; int com; dsu(int _n) : n(_n) { p.resize(n); com = n; iota(p.begin(), p.end(), 0); } inline int get(int x) { return (x == p[x] ? x : (p[x] = get(p[x]))); } inline bool unite(int x, int y) { x = get(x); y = get(y); if (x != y) { p[x] = y; --com; return true; } return false; } }; int main() { ios_base::sync_with_stdio(false); cin.tie(0); const int n = 5; vector> c(n, vector(n)); long long total = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> c[i][j]; total += c[i][j]; } } long long ans = (long long) 1e18; const vector dx = {-1, 0, 1, 0}; const vector dy = {0, -1, 0, 1}; vector was(1 << (n * n)); function On = [&](int mask, int x, int y) { return (mask >> (x * n + y)) & 1; }; function DFS = [&](int mask, long long sum) { was[mask] = 1; long long res = abs(sum - (total - sum)); if (res < ans) { dsu d(n * n); for (int x = 0; x < n; x++) { for (int y = 0; y < n; y++) { if (x - 1 >= 0 && On(mask, x, y) == On(mask, x - 1, y)) { d.unite(x * n + y, (x - 1) * n + y); } if (y - 1 >= 0 && On(mask, x, y) == On(mask, x, y - 1)) { d.unite(x * n + y, x * n + y - 1); } } } if (d.com <= 2) { ans = res; } } for (int x = 0; x < n; x++) { for (int y = 0; y < n; y++) { if (On(mask, x, y)) { continue; } for (int k = 0; k < 4; k++) { int xk = x + dx[k]; int yk = y + dy[k]; if (0 <= xk && xk < n && 0 <= yk && yk < n && On(mask, xk, yk) && !was[mask | (1 << (x * n + y))]) { DFS(mask | (1 << (x * n + y)), sum + c[x][y]); } } } } }; DFS(1, c[0][0]); cout << ans << '\n'; return 0; }