forked from imdhanish/HackerEarth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrix Sum
More file actions
61 lines (52 loc) · 1.17 KB
/
Matrix Sum
File metadata and controls
61 lines (52 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*You are given a matrix. You need to print the sum of all the numbers in the rectangle which has as the top left corner and as the bottom right corner.
Input:
First line contains two integers, N and M, number of rows and number of columns in the matrix.
Next N lines contains M space separated integers, elements of the matrix.
Next line contains an integer, Q, number of queries.
Each query contains two space separated integers, X and Y.
Output:
For each query, print the sum of all the numbers in the rectangle which has as the top left corner and as the bottom right corner.
Constraints:
elements of matrix
SAMPLE INPUT
3 3
1 2 3
4 5 6
7 8 9
2
3 3
2 3
SAMPLE OUTPUT
45
21
*/
#include <iostream>
using namespace std;
int sumarr[1001][1001]={0};
int ar[1001][1001];
int findsum(int ar[1001][1001],int X,int Y){
if((X<1)||(Y<1))
return 0;
if(sumarr[X][Y]!=0)
return sumarr[X][Y];
else
sumarr[X][Y]=findsum(ar,X-1,Y)+findsum(ar,X,Y-1)-findsum(ar,X-1,Y-1)+ar[X][Y];
return sumarr[X][Y];
}
int main()
{
int N,M,i,j,no,Q,X,Y,sum;
cin>>N>>M;
for(i=1;i<=N;i++){
for(j=1;j<=M;j++){
cin>>no;
ar[i][j]=no;
}
}
cin>>Q;
while(Q-->0){
cin>>X>>Y;
sum=findsum(ar,X,Y);
cout<<sum<<endl;
}
}