#define _USE_MATH_DEFINES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; const int N = 5; const long long INF = LLONG_MAX / 2; const int dy[] = {0, 1, 0, -1}; const int dx[] = {-1, 0, 1, 0}; bool check(const vector >& cake) { for(int i=0; i<2; ++i){ int sy = -1; int sx = -1; for(int y=0; y > used(N, vector(N, false)); queue > q; used[sy][sx] = true; q.push(make_pair(sy, sx)); while(!q.empty()){ int y, x; tie(y, x) = q.front(); q.pop(); for(int j=0; j<4; ++j){ int y2 = y + dy[j]; int x2 = x + dx[j]; if(!(0 <= y2 && y2 < N && 0 <= x2 && x2 < N)) continue; if(!used[y2][x2] && (cake[y2][x2] == i || cake[y2][x2] == -1)){ used[y2][x2] = true; q.push(make_pair(y2, x2)); } } } for(int y=0; y& val, vector >& cake, int k, long long diff) { if(k == N * N) return abs(diff); if(!check(cake)) return INF; long long ans = INF; for(int i=0; i<2; ++i){ long long diff2 = diff + val[k] * (i == 0 ? 1 : -1); cake[k/5][k%5] = i; ans = min(ans, solve(val, cake, k+1, diff2)); cake[k/5][k%5] = -1; } return ans; } int main() { vector val(N*N); for(int i=0; i> val[i]; vector > cake(N, vector(N, -1)); cout << solve(val, cake, 0, 0) << endl; return 0; }