import std.conv, std.functional, std.range, std.stdio, std.string; import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, std.numeric, std.regex, std.typecons; import core.bitop; class EOFException : Throwable { this() { super("EOF"); } } string[] tokens; string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; } int readInt() { return readToken.to!int; } long readLong() { return readToken.to!long; } real readReal() { return readToken.to!real; } bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } } bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } } int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; } int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); } int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); } int root(int[] uf, int u) { return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u])); } bool connect(int[] uf, int u, int v) { u = uf.root(u); v = uf.root(v); if (u == v) return false; if (uf[u] > uf[v]) swap(u, v); uf[u] += uf[v]; uf[v] = u; return true; } enum N = 5; enum INF = 10L^^18; void main() { alias Pt = Tuple!(int, "x", int, "y"); Pt[] ins, outs; foreach (x; 1 .. N - 1) foreach (y; 1 .. N - 1) { ins ~= Pt(x, y); } foreach (x; 0 .. N - 1) outs ~= Pt(x, 0); foreach (y; 0 .. N - 1) outs ~= Pt(N - 1, y); foreach_reverse (x; 1 .. N) outs ~= Pt(x, N - 1); foreach_reverse (y; 1 .. N) outs ~= Pt(0, y); const insLen = cast(int)(ins.length); const outsLen = cast(int)(outs.length); debug { writeln("ins = ", ins); writeln("outs = ", outs); } try { for (; ; ) { auto C = new long[][](N, N); foreach (x; 0 .. N) foreach (y; 0 .. N) { C[x][y] = readLong(); } long ans = INF; foreach (p; 0 .. 1 << insLen) { foreach (a; 0 .. insLen) foreach (w; 0 .. insLen + 1) { auto col = new int[][](N, N); foreach (i; 0 .. insLen) { if (p & 1 << i) { col[ins[i].x][ins[i].y] = 1; } } foreach (i; a .. a + w) { col[outs[i % $].x][outs[i % $].y] = 1; } auto uf = new int[](N * N); uf[] = -1; foreach (x; 0 .. N) foreach (y; 0 .. N) { if (x > 0 && col[x - 1][y] == col[x][y]) { uf.connect((x - 1) * N + y, x * N + y); } if (y > 0 && col[x][y - 1] == col[x][y]) { uf.connect(x * N + (y - 1), x * N + y); } } auto szss = new int[][2]; foreach (x; 0 .. N) foreach (y; 0 .. N) { if (uf[x * N + y] < 0) { szss[col[x][y]] ~= -uf[x * N + y]; } } if (szss.all!"a.length == 1") { auto sums = new long[2]; foreach (x; 0 .. N) foreach (y; 0 .. N) { sums[col[x][y]] += C[x][y]; } chmin(ans, abs(sums[0] - sums[1])); } } } writeln(ans); } } catch (EOFException e) { } }