Array Play
InterviewTime limit2sMemory limit512 MB
Given an N by N grid and M rectangle-add operations, output the final sum of each row and each column.
- Level
Medium4 of 10
- Topics
- Prefix sum, Array, Implementation, Simulation
- Solved
- No attempts yet
Problem
There is a two-dimensional integer array with rows and columns. denotes the value of the element in row and column .
Consider a game on this array that applies a total of operations.
Each operation is given by five integers satisfying , , and . The operation adds to every inside the rectangle from to .
For example, take and , and apply the following three operations in order.
- Operation 1:
- Operation 2:
- Operation 3:
Before any operation, is as follows.
A = [ [ 1 2 3 ]
[ 4 5 6 ]
[ 7 8 9 ] ].
Applying operation 1 changes the six elements in the first two rows:
A = [ [ 4 5 6 ]
[ 7 8 9 ]
[ 7 8 9 ] ].
After applying operation 2:
A = [ [ 4 5 6 ]
[ 7 3 9 ]
[ 7 3 9 ] ].
After applying operation 3:
A = [ [ 5 6 6 ]
[ 8 4 9 ]
[ 8 4 9 ] ].
After all three operations, you want the sum of the elements of each row and the sum of the elements of each column of the resulting array. In the example above, the row sums are (row 1 to row 3) and the column sums are (column 1 to column 3).
Given , , a two-dimensional array , and operations, write a program that computes the row sums and column sums after applying all operations to the array.
Input
The first line contains the number of test cases ().
For each test case, the first line contains two integers and separated by a space (, ).
The next lines give the two-dimensional array , where the -th line is the -th row. The -th integer in each line is the value of the element in the -th column. Each element of is an integer between and inclusive.
The next lines each contain five integers separated by spaces. It always holds that , , and .
Output
For each test case, print the answer on two lines.
The first line contains the row sums separated by spaces (row 1 to row ).
The second line contains the column sums separated by spaces (column 1 to column ).
Hint
The first test case is described in the problem statement.
For the second test case, applying the operation changes the array to the following.
[ [ -20 -10 ]
[ 0 10 ] ].
Thus the row sums are and the column sums are .
For the third test case, applying all operations leaves a array whose element is 2000.
PyPy is faster than Python in most cases, so if your Python solution exceeds the time limit, it is better to use PyPy.