#include #define rep(i, n) for (int i = 0; i < (n); i++) #define repr(i, n) for (int i = (n) - 1; i >= 0; i--) using namespace std; using ll = long long; struct unionfind { vector dat; unionfind(int n) : dat(n) { rep(i, n) dat[i] = i; } int find(int x) { if (x == dat[x]) return x; return dat[x] = find(dat[x]); } void unite(int x, int y) { x = find(x); y = find(y); dat[x] = dat[y] = max(x, y); } }; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); ll C[5][5]; rep(i, 5) rep(j, 5) cin >> C[i][j]; int color[5][5] = {}; ll ans = 1e18; auto dfs = [&](auto dfs, int k, unionfind uf) -> void { if (k == 5) { int st = 0; rep(i, 25) st |= 1 << uf.find(i); if (__builtin_popcount(st) != 2) return; ll x = 0; /* rep(i, 5) { rep(j, 5) { cout << color[i][j]; } cout << endl; } cout << endl; */ rep(i, 5) rep(j, 5) { if (color[i][j]) x += C[i][j]; else x -= C[i][j]; } ans = min(ans, abs(x)); return; } rep(x, 1 << 5) { unionfind uf2 = uf; rep(j, 5) color[k][j] = x >> j & 1; rep(j, 4) { if (color[k][j] == color[k][j + 1]) uf2.unite(k*5+j, k*5+j+1); } if (k > 0) { rep(j, 5) if (color[k][j] == color[k-1][j]) uf2.unite(k*5+j, k*5+j-5); } int xs = 0; rep(j, 5) xs |= 1 << color[k][j]; int st = 0; rep(i, (k+1)*5) { if (uf2.find(i) < k * 5) { if ((1 << color[i / 5][i % 5] & xs) != 0) st = 0x7; st |= 1 << uf2.find(i); } } if (__builtin_popcount(st) < 2) { dfs(dfs, k + 1, uf2); } } }; unionfind uf(25); dfs(dfs, 0, uf); cout << ans << endl; }