差分-前戳和-二维前戳和

import os
import sys
a, b = map(int, input().split())
number = list(map(int, input().split()))
# number = [0] + number + [0]
# for i in range(a+2):
#   number[i]=number[i]-number[i-1]
# print(number)
ab = (a + 2) * [0]

ans = []
for i in range(int(b)):
    c = list(map(int, input().split()))
    ans.append(c)
# print(ans)
for i in ans:
    # print(i)
    fir = i[0]
    last = i[1]
    seats = i[2]

    ab[fir] += seats
    ab[last + 1] -= seats
# print(ab)

for i in range(1, a+1):
    ab[i] += ab[i - 1]
# print(ab)
print(' '.join(str(max(number[i-1] + ab[i], 0)) for i in range(1,a+1)))
if __name__ == "__main__":
    n, m = map(int, input().split())
    nums = list(map(int, input().split()))
    prefix = [0] * (n + 10)					# 前缀和数组
    for i in range(n):
        prefix[i+1] = prefix[i] + nums[i]   # 求前缀和
    for i in range(m):
        l, r = map(int, input().split())
        print(prefix[r] - prefix[l-1])      # 求部分和
if __name__ == "__main__":
    n, m, q = map(int, input().split())
    nums = []
    for _ in range(n):
        nums.append([int(i) for i in input().split()])
    
    # 1.计算前缀和
    s = [[0]*(m+1) for _ in range(n+1)]
    for i in range(1, n+1):
        for j in range(1, m+1):
            s[i][j] = nums[i-1][j-1] + s[i-1][j] + s[i][j-1] - s[i-1][j-1]
    
    ans = []
    # 2.计算区域和
    for _ in range(q):
        x1, y1, x2, y2 = map(int, input().split())
        ans.append(s[x2][y2] - s[x2][y1-1] - s[x1-1][y2] + s[x1-1][y1-1])
    print('\n'.join(map(str, ans)))
# 核心
def insert(b, l, r, c):
    b[l] += c
    b[r+1] -= c


if __name__ == "__main__":
    n, m = map(int, input().split())
    a = [0] * (n + 10)  # 原数组
    b = [0] * (n + 10)  # 差分数组
    nums = list(map(int, input().split()))
    for index, val in enumerate(nums):
        a[index+1] = val
        
    # 构建初始差分数组b[]
    for i in range(1, n+1):
        insert(b, i, i, a[i])
    
    # 根据题意修改差分数组
    while m > 0:
        m -= 1
        l, r, c = map(int, input().split())
        insert(b, l, r, c)
        
    # 利用修改后的差分数组重新计算前缀和
    for i in range(1, n+1):
        b[i] += b[i-1]
    for i in range(1, n+1):
        print(b[i], end=" ")

你可能感兴趣的:(python,开发语言)