#K9381. Dynamic 2D Matrix Query
Dynamic 2D Matrix Query
Dynamic 2D Matrix Query
You are given a 2D matrix with n rows and m columns. You need to implement a data structure that supports two types of operations:
- update row col val: Update the element at position (row, col) to val.
- sum r1 c1 r2 c2: Calculate the sum of all elements within the submatrix whose top-left corner is (r1, c1) and bottom-right corner is (r2, c2) (inclusive).
The operations are given as queries in the input. For every sum
query, output the corresponding result.
In mathematical terms, if the matrix is denoted by \( A \), then the sum query should return:
[ S = \sum_{i=r1}^{r2} \sum_{j=c1}^{c2} A[i][j] ]
It is guaranteed that the queries are valid. Use standard input and output for reading and writing data.
inputFormat
The first line contains two integers n and m, representing the number of rows and columns, respectively.
The next n lines each contain m integers, representing the initial 2D matrix.
The following line contains an integer q that represents the number of queries.
Then q lines follow. Each line is either:
update row col val
- to update the matrix at position (row, col) to val.sum r1 c1 r2 c2
- to perform a sum query over the submatrix defined by the top-left corner (r1, c1) and bottom-right corner (r2, c2).
outputFormat
For each sum
query, output the resulting sum on a new line.
3 3
1 2 3
4 5 6
7 8 9
3
sum 0 0 1 1
sum 1 1 2 2
sum 0 0 2 2
12
28
45
</p>