Matrix Sum
Very Easy
52.0% success
7,342 attempts
1s time
256MB memory
1024KB max code

You are given a \(N*M\) matrix. You need to print the sum of all the numbers in the rectangle which has \((1, 1)\) as the top left corner and \((X, Y)\) 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 \((1, 1)\) as the top left corner and \((X, Y)\) as the bottom right corner.

Constraints:
\(1 \le N, M \le 10^3\)
\(1 \le\) elements of matrix \(\le 10^3\)
\(1 \le X \le N\)
\(1 \le Y \le M\)
\(1 \le Q \le 10^5\)

Examples
Input
3 3
1 2 3
4 5 6
7 8 9
2
3 3
2 3
Output
45
21
Explanation

In the first query, \(X = 3, Y = 3\)
So rectangle formed will be

1 2 3
4 5 6
7 8 9

Sum of all the elements in the rectangle is \((1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9) = 45\)

In the second query, \(X = 2, Y = 3\)

So the rectangle will be

1 2 3
4 5 6

Sum of all the elements in the rectangle is \((1 + 2 + 3 + 4 + 5 + 6) = 21\)

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading Editor...