题目描述
输入一个n行m列的整数矩阵,再输入q个操作,每个操作包含五个整数x1, y1, x2, y2, c,其中(x1, y1)和(x2, y2)表示一个子矩阵的左上角坐标和右下角坐标。
每个操作都要将选中的子矩阵中的每个元素的值加上c。
请你将进行完所有操作后的矩阵输出。
输入格式
第一行包含整数n,m,q。
接下来n行,每行包含m个整数,表示整数矩阵。
接下来q行,每行包含5个整数x1, y1, x2, y2, c,表示一个操作。
输出格式
共 n 行,每行 m 个整数,表示所有操作进行完毕后的最终矩阵。
数据范围
1≤n,m≤1000,
1≤q≤100000,
1≤x1≤x2≤n,
1≤y1≤y2≤m,
−1000≤c≤1000,
−1000≤矩阵内元素的值≤1000
输入样例:
3 4 3
1 2 2 1
3 2 2 1
1 1 1 1
1 1 2 2 1
1 3 2 3 2
3 1 3 4 1
输出样例:
2 3 4 1
4 3 4 1
2 2 2 2
代码
from typing import List
def finite_difference(sums: List[List[int]]) -> List[List[int]]:
"""
Args:
sums (List[List[int]]): the origin second dimention list.
Returns:
(List[List[int]]): the finite difference of the origin sums.
"""
differences = [[0 for j in i] for i in sums]
for i in range(len(sums)):
for j in range(len(sums[i])):
add_range(differences, i, j, i, j, sums[i][j])
return differences
def add_range(differences: List[List[int]], x1: int, y1: int, x2: int, y2: int, value: int):
"""
Args:
differences (List[List[int]]): the finite difference of the origin sums.
x1 (int): the x of the upper left index.
y1 (int): the y of the upper left index.
x2 (int): the x of the bottom right index.
y2 (int): the y of the bottom right index.
value (int): add value to the origin sums[x1:x2+1][y1:y2+1].
"""
differences[x1][y1] += value
if x2 + 1 < len(differences):
differences[x2 + 1][y1] -= value
if y2 + 1 < len(differences[x1]):
differences[x1][y2 + 1] -= value
if x2 + 1 < len(differences) and y2 + 1 < len(differences[x2 + 1]):
differences[x2 + 1][y2 + 1] += value
def prefix_sum(differences: List[List[int]]) -> List[List[int]]:
"""
Args:
differences (List[List[int]]): the source second dimension list.
Returns:
List[List[int]]: the prefix sums of the given differences. The item (i,j) equals to sum(difference[:i+1][:j+1]).
"""
sums = [[0 for _ in range(len(differences[0])+1)]]
sums += [[0] + d[:] for d in differences]
for i in range(1, len(sums)):
for j in range(1, len(sums[i])):
sums[i][j] += sums[i-1][j] + sums[i][j-1] - sums[i-1][j-1]
return [s[1:] for s in sums[1:]]
def add_ranges(matrix: List[List[int]], operations: List[int]) -> List[int]:
differences = finite_difference(matrix)
for x1, y1, x2, y2, value in operations:
add_range(differences, x1-1, y1-1, x2-1, y2-1, value)
return prefix_sum(differences)
if __name__ == '__main__':
from sys import stdin
def readline() -> List[int]:
return [int(i) for i in stdin.readline().split()]
N, M, Q = readline()
matrix = [readline() for _ in range(N)]
operations = [readline() for _ in range(Q)]
for line in add_ranges(matrix, operations):
print(' '.join((str(i) for i in line)))