fork download
  1. #include<bits/stdc++.h>
  2. #define ull unsigned long long
  3. #define ll long long
  4. #define mp make_pair
  5. #define A first
  6. #define B second
  7. #define MIN (1<<31)
  8. #define MAX (1<<31) - 1
  9. #define MOD 1000000007
  10. using namespace std;
  11.  
  12. #define N 1005
  13.  
  14. ll A[N][N]; //matrix
  15. ll dp[N][N];
  16.  
  17. int n,m;
  18.  
  19. ll calc(int x,int y){ //recursive calculates the sum of the sub-rectangle {(1,1) to (x,y)}
  20. if(x<1 || y<1 || x>n || y>m) return 0;
  21. if(dp[x][y]!=-1) return dp[x][y];
  22. dp[x][y] = calc(x-1,y) + calc(x,y-1);
  23. dp[x][y] -= calc(x-1,y-1);
  24. dp[x][y] += A[x][y];
  25. return dp[x][y];
  26. }
  27.  
  28. int main(){
  29. ios_base::sync_with_stdio(false);
  30. cin.tie(NULL);
  31.  
  32. memset(dp,-1,sizeof(dp));
  33. cin>>n>>m; //input the dimensions
  34. for(int i=1;i<=n;i++){
  35. for(int j=1;j<=m;j++) cin>>A[i][j]; //take input
  36. }
  37. dp[1][1]=A[1][1]; //base case
  38. int c,x1,y1,x2,y2;
  39. ll ans=0;
  40. cin>>c; //no of queries
  41. for(int i=0;i<c;i++){
  42. cin>>x1>>y1>>x2>>y2; //input of coordinates
  43. ans = calc(x2,y2); //the formula for calculating the sum of sub-rectangle
  44. ans -= (calc(x1-1,y2) + calc(x2,y1-1)); //...
  45. ans += calc(x1-1,y1-1); //...
  46. cout<<ans<<endl; //output of the answer
  47. }
  48. return 0;
  49. }
  50.  
  51.  
  52.  
Success #stdin #stdout 0s 19256KB
stdin
4   4 
3   4   15  23 
14  20  12  9
3   8   12  15
12  20  7   5
2
2   2   3   4 
4   2   4   2
stdout
76
20