#include <bits/stdc++.h>
#define ll long long
#define pii pair<int,int>
#define fi first
#define se second
#define pb push_back
using namespace std;
ll pref[501][501];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int n,m,L,R,M,i,j,k;
ll x,ans=1e18,now,tb,a,b,nw;
cin>>n>>m>>a>>b;
if(a > b) swap(a,b);
for(i=1;i<=n;i++){
for(j=1;j<=m;j++){
cin>>x;
pref[i][j] = x+pref[i-1][j]+pref[i][j-1]-pref[i-1][j-1];
if(pref[i][j] < a){
ans = min(ans,a+b-2*pref[i][j]);
continue;
}
if(pref[i][j] >= a and pref[i][j] <= b or x >= a and x <= b){
cout<<b-a;
return 0;
}
for(k=j;k>=1;k--){
// ambil k,j
now = pref[i][j]-pref[i][k-1];
L = 1, R = i;
while(L <= R){
M = (L+R)/2;
// ambil row M,i
tb = -pref[M-1][j]+pref[M-1][k-1];
nw = now+tb;
if(nw < a){
ans = min(a+b-2*nw,ans);
R = M-1;
continue;
}
if(nw > b){
ans = min(ans,2*nw-a-b);
L = M+1;
continue;
}
cout<<b-a;
return 0;
}
}
}
}
cout<<ans;
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... |