#include <bits/stdc++.h>
//#include "includeall.h"
#define endl '\n'
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define lb lower_bound
#define ub upper_bound
#define input(x) scanf("%lld", &x);
#define input2(x, y) scanf("%lld%lld", &x, &y);
#define input3(x, y, z) scanf("%lld%lld%lld", &x, &y, &z);
#define input4(x, y, z, a) scanf("%lld%lld%lld%lld", &x, &y, &z, &a);
#define print(x, y) printf("%lld%c", x, y);
#define show(x) cerr << #x << " is " << x << endl;
#define show2(x,y) cerr << #x << " is " << x << " " << #y << " is " << y << endl;
#define show3(x,y,z) cerr << #x << " is " << x << " " << #y << " is " << y << " " << #z << " is " << z << endl;
#define all(x) x.begin(), x.end()
#define discretize(x) sort(x.begin(), x.end()); x.erase(unique(x.begin(), x.end()), x.end());
#define FOR(i, x, n) for (ll i =x; i<=n; ++i)
#define RFOR(i, x, n) for (ll i =x; i>=n; --i)
#pragma GCC optimize("O3","unroll-loops")
using namespace std;
mt19937_64 rnd(chrono::steady_clock::now().time_since_epoch().count());
typedef long long ll;
typedef long double ld;
typedef pair<ld, ll> pd;
typedef pair<string, ll> psl;
typedef pair<ll, ll> pi;
typedef pair<pi, ll> pii;
typedef pair<pi, pi> piii;
ll dp[505][505];
// Returns the sum of the submatrix with top-left (x1, y1) and bottom-right (x2, y2)
inline ll cal(ll x1, ll y1, ll x2, ll y2) {
return dp[x2][y2] - dp[x1-1][y2] - dp[x2][y1-1] + dp[x1-1][y1-1];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
ll r, c, a, b;
cin >> r >> c >> a >> b;
// Build the prefix sum array
for (ll i = 1; i <= r; ++i) {
for (ll j = 1; j <= c; ++j) {
cin >> dp[i][j];
dp[i][j] += dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1];
}
}
ll ans = LLONG_MAX;
// Iterate over all choices for bottom-right (i, j) and left column k
for (ll i = 1; i <= r; ++i) {
for (ll j = 1; j <= c; ++j) {
for (ll k = 1; k <= j; ++k) {
// Instead of binary searching for the optimal top row,
// we use the observation that the best cost is determined
// by the maximum (using top row 1) and minimum (using top row i) sums.
ll S_top = cal(1, k, i, j);
ll S_bot = cal(i, k, i, j);
ll curCost;
if(S_top < a)
curCost = (a - S_top) + (b - S_top);
else if(S_bot > b)
curCost = (S_bot - a) + (S_bot - b);
else
curCost = b - a; // there is some x with F(x) in [a, b]
ans = min(ans, curCost);
}
}
}
cout << ans << endl;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |