题目描述
输入一个长度为n的整数序列。
接下来输入m个操作,每个操作包含三个整数l, r, c,表示将序列中[l, r]之间的每个数加上c。
请你输出进行完所有操作后的序列。
输入格式
第一行包含两个整数n和m。
第二行包含n个整数,表示整数序列。
接下来m行,每行包含三个整数l,r,c,表示一个操作。
输出格式
共一行,包含n个整数,表示最终序列。
数据范围
1≤n,m≤100000,
1≤l≤r≤n,
−1000≤c≤1000,
−1000≤整数序列中元素的值≤1000
输入样例:
6 3
1 2 2 1 2 1
1 3 1
3 5 1
1 6 1
输出样例:
3 4 5 3 4 2
代码
from typing import List
def finite_difference(sums: List[int]) -> List[int]:
"""
Args:
sums (List[int]): the origin list.
Returns:
(List[int]): the finite difference of the origin sums.
"""
differences = [0 for i in range(len(sums))]
for index, value in enumerate(sums):
add_range(differences, index, index, value)
return differences
def add_range(differences: List[int], left: int, right: int, value: int):
"""
Args:
differences (List[int]): the finite difference of the origin sums.
left (int): the left index.
right (int): the right index.
value (int): add value to the origin sums[left:right+1].
"""
differences[left] += value
if right+1 < len(differences):
differences[right+1] -= value
def prefix_sum(differences: List[int]):
"""
Args:
differences (List[int]): the source list.
Returns:
List[int]: the prefix sums of the given differences. The item (i) equals to sum(difference[:i+1]).
"""
sums = differences.copy()
for index in range(len(sums)-1):
sums[index+1] += sums[index]
return sums
def add_ranges(numbers: List[int], operations: List[List[int]]) -> List[int]:
differences = finite_difference(numbers)
for left, right, value in operations:
add_range(differences, left-1, right-1, value)
return prefix_sum(differences)
if __name__ == '__main__':
from sys import stdin
def readline():
return [int(i) for i in stdin.readline().split()]
N, M = readline()
numbers = readline()
operations = [readline() for _ in range(M)]
print(" ".join((str(i) for i in add_ranges(numbers, operations))))