#include <bits/stdc++.h>
using namespace std;
long long r, s, a, b;
long long grid[505][505];
long long prefix[505][505];
long long getsum(long long top, long long bottom, long long pos) {
return prefix[bottom][pos] - prefix[top - 1][pos];
}
int main() {
cin >> r >> s >> a >> b;
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= s; j++) {
cin >> grid[i][j];
prefix[i][j] = prefix[i-1][j] + grid[i][j];
}
}
long long ans = 2e12;
for (int i = 1; i <= r; i++) {
for (int j = i; j <= r; j++) {
long long sum = 0;
long long beg = 1, en = 0;
while (en <= s && beg <= s) {
if (en < beg) {
en++;
continue;
}
sum += getsum(i, j, en);
ans = min(ans, abs(a - sum) + abs(b - sum));
while (sum > max(a, b)) {
sum -= getsum(i, j, beg);
ans = min(ans, abs(a - sum) + abs(b - sum));
beg++;
}
en++;
}
}
}
cout << ans;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |