最后3个超时,只有70分,求助

P3372 【模板】线段树 1

Biaoaowowo @ 2023-03-19 21:36:55

class SegTree:
    def __init__(self, L):
        self.length = len(L)
        self.Arr = [0] * (4 * self.length + 1)
        self.Lazy = [0] * (4 * self.length + 1)
        self.buildTree(1, 1, self.length, [0] + L)

    def buildTree(self, root_idx, left, right, List):
        if left == right:
            self.Arr[root_idx] = List[left]
            return
        mid = (left + right) >> 1
        left_child = root_idx << 1
        right_child = (root_idx << 1) + 1
        self.buildTree(left_child, left, mid, List)
        self.buildTree(right_child, mid + 1, right, List)
        self.Arr[root_idx] = self.Arr[left_child] + self.Arr[right_child]

    def Insert_and_GetSum(self, root_idx, left, right, s, t, value):
        if right < s or left > t: return 0
        mid, left_child, right_child = (left + right) >> 1, root_idx << 1, (root_idx << 1) + 1
        ans = 0

        if left >= s and right <= t:
            self.Lazy[root_idx] += value
            return self.Arr[root_idx] + (right - left + 1) * self.Lazy[root_idx]
        if self.Lazy[root_idx] != 0 and left != right:
            self.Arr[root_idx] += (right - left + 1) * self.Lazy[root_idx]
            self.Lazy[left_child] += self.Lazy[root_idx]
            self.Lazy[right_child] += self.Lazy[root_idx]
            self.Lazy[root_idx] = 0
        ans += self.Insert_and_GetSum(left_child, left, mid, s, t, value)
        ans += self.Insert_and_GetSum(right_child, mid + 1, right, s, t, value)
        self.Arr[root_idx] = self.Arr[left_child] + self.Lazy[left_child] * (mid - left + 1) + self.Arr[right_child] + \
                             self.Lazy[right_child] * (right - mid)
        return ans

n, m = map(int, input().split())
Tree = SegTree(list(map(int, input().split())))
for i in range(m):
    cmd = tuple(map(int, input().split()))
    if cmd[0] == 1:
        (Tree.Insert_and_GetSum(1, 1, Tree.length, cmd[1], cmd[2], cmd[3]))
    elif cmd[0] == 2:
        print(Tree.Insert_and_GetSum(1, 1, Tree.length, cmd[1], cmd[2], 0))

|