This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int MAX = 615;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
#define pb push_back
#define sz(x) (int) x.size()
#define fr first
#define sc second
#define mp make_pair
#define all(x) x.begin(), x.end()
#define dbg(x) cerr << #x << ": " << "[ " << x << " ]\n"
ll n, m, a, b, t[MAX][MAX], ps[MAX][MAX];
ll query(int x, int y, int u, int v){
    return ps[u][v] - ps[x - 1][v] - ps[u][y - 1] + ps[x - 1][y - 1];
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); 
    cin >> n >> m >> a >> b;
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= m; j++){
            cin >> t[i][j];
        }
    }    
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= m; j++){
            ps[i][j] = ps[i - 1][j] + ps[i][j - 1] - ps[i - 1][j - 1] + t[i][j]; 
        }
    }
    ll ans = INF;
    if(a > b) swap(a, b);
    for(int i = 1; i <= n; i++){
         for(int j = i; j <= n; j++){
            ll p = 0;
            for(int k = 1; k <= m; k++){
                ll val = query(i, 1, j, k);
                while(p < k && val - query(i, 1, j, p) >= a) p++;
                
                if(p < k) ans = min(ans, abs(val - query(i, 1, j, p) - a) + abs(val - query(i, 1, j, p) - b));
                if(p >= 1) ans = min(ans, abs(val - query(i, 1, j, p - 1) - a) + abs(val - query(i, 1, j, p - 1) - b));
            }
         }
    }
       
    cout << ans << '\n';
    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... |