This is a competitive programming style question, so let’s define the problem statement with sample input-output and input constraints.
Given a matrix consisting of integers, answer queries on the matrix of type ; i.e., sum the elements in the submatrix with top left corner and bottom right corner .
The first line of input consists of two space-separated integers, and .
The next lines contain M space-separated integers that each represent the matrix.
The next line contains a single integer that represents the number of queries .
The next lines contain four space-separated integers , respecitvely.
For each , print a single integer, i.e., the sum of the sub-matrix as described in the problem.
5 5
1 4 7 3 2
3 4 2 5 9
6 1 6 2 1
2 5 8 7 6
3 6 9 8 3
2
2 2 3 5
3 2 5 4
30
52
For query -> , the corresponding submatrix is:
The sum of the elements is:
Pretty straightforward. For each query, loop over the submatrix and calculate the sum.
Each query will be answered in . The time complexity of the solution will be .
With given constraints on and , we can answer a handful of queries in a few seconds, but definitely not a million queries.
The code for brute force is:
5 51 4 7 3 23 4 2 5 96 1 6 2 12 5 8 7 63 6 9 8 322 2 3 53 2 5 4
We can extend the concept of prefix sums in 1-D arrays to 2 dimensions.
Quick recap. The prefix sum in the 1-D array is defined as:
Then, the sum of a subarray is .
Let’s define the prefix sum in 2-D, say is the sum of elements of the submatrix with top left corner as and bottom right corner as , or .
Let’s see how we can use the prefix sum matrix to get the sum of any submatrix in time:
The illustration below will help you to visualize the formula:
Each query can be answered in if we have the array.
The array can be computed in in a similar way as above. Here is the formula:
If we iterate the matrix from left to right and top to bottom, at we would already have the values at , and . So, calculating the value of is a constant time operation, i.e., .
Pre-computing the entire matrix takes time.
By using , we can answer each query in .
Thus, the total time complexity is, .
#include <iostream>#include <vector>#include <utility>#include <fstream>using namespace std;int main() {ifstream cin("input.txt");int N, M, Q;cin >> N >> M;int A[N][M];for (int i = 0; i < N; i++)for (int j = 0; j < M; j++)cin >> A[i][j];cin >> Q;int pref[N][M];for (int i = 0; i < N ; i++){for (int j = 0; j < M; j++) {pref[i][j] = A[i][j];if (i > 0) pref[i][j] += pref[i-1][j];if (j > 0) pref[i][j] += pref[i][j-1];if (i > 0 && j > 0) pref[i][j] -= pref[i-1][j-1];}}while (Q--) {int x1, y1, x2, y2 ;cin >> x1 >> y1 >> x2 >> y2;x1 --; y1--; x2--; y2--;int sum = pref[x2][y2];if (y1 > 0) sum -= pref[x2][y1-1];if (x1 > 0) sum -= pref[x1-1][y2];if (x1 > 0 and y1 > 0) sum += pref[x1-1][y1-1];cout << sum << "\n";}return 0;}