fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long
  4. //#define ll int
  5. typedef long long ll;
  6. const int MAXN = 507;
  7. int a[MAXN][MAXN], pre[MAXN][MAXN], n, m, A, B, ans = INT_MAX;
  8.  
  9. void precompute(){
  10. cin >> n >> m >> A >> B;
  11. for(int i = 1; i <= n; i++)
  12. for(int j = 1; j <= m; j++) cin >> a[i][j];
  13. for(int i = 1; i <= n; i++)
  14. for(int j = 1; j <= m; j++) pre[i][j] = pre[i][j - 1] + a[i][j] + pre[i - 1][j] - pre[i - 1][j - 1];
  15. }
  16.  
  17. ll get2(int x, int y, int u, int v){
  18. return pre[u][v] - pre[x - 1][v] - pre[u][y - 1] + pre[x - 1][y - 1];
  19. }
  20.  
  21. ll get1(vector <int> &pre, int L, int R){
  22. return pre[R] - pre[L - 1];
  23. }
  24.  
  25. signed main(){
  26. ios_base::sync_with_stdio(0);
  27. cout.tie(0);
  28. cin.tie(0);
  29. freopen("hub03.inp", "r", stdin);
  30. freopen("hub03.out", "w", stdout);
  31. precompute();
  32. for(int x = 1; x <= n; x++){
  33. for(int u = x; u <= n; u++){
  34. vector <int> pre2(m + 1, 0);
  35. for(int v = 1; v <= m; v++)pre2[v] = get2(x, 1, u, v);
  36. int L = 1;
  37. for(int R = 1; R <= m; R++){
  38. while(pre2[R] - pre2[L - 1] > A and L < R) L++;
  39. int S1 = pre2[R] - pre2[L - 1];
  40. ans = min(ans, abs(A - S1) + abs(B - S1));
  41. if(L - 1){
  42. int S2 = pre2[R] - pre2[L - 2];
  43. ans = min(ans, abs(A - S2) + abs(B - S2));
  44. }
  45. }
  46. }
  47. }
  48. cout << ans;
  49. }
  50.  
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
Standard output is empty