求助:为什么会超时如何修改

P3372 【模板】线段树 1

dyegral @ 2023-10-30 22:55:29

照着网上的文章写的线段树,最后三组测试用例会超时

MAXN = int(1e5 + 5)

n, m = (int(x) for x in input().strip().split(' '))

tree = [0] * (MAXN * 4)
mark = [0] * (MAXN * 4)

def push_down(p, size):
  if size <= 1: return
  # 左子节点
  tree[p * 2] += mark[p] * (size - size // 2)
  mark[p * 2] += mark[p]
  # 右子节点
  tree[p * 2 + 1] += mark[p] * (size // 2)
  mark[p * 2 + 1] += mark[p]
  mark[p] = 0

def update(l, r, d, p = 1, cl = 1, cr = n):
  if cr < l or cl > r: return
  if cl >= l and cr <= r:
    tree[p] += d * (cr - cl + 1)
    mark[p] += d
    return
  if cl <= r or cr >= l:
    push_down(p, cr - cl + 1)
    mid = cl + (cr - cl) // 2
    if mid >= l: update(l, r, d, p * 2, cl, mid)
    if mid < r: update(l, r, d, p * 2 + 1, mid + 1, cr)
    tree[p] = tree[p * 2] + tree[p * 2 + 1]  

def query(l, r, p = 1, cl = 1, cr = n):
  if cl >= l and cr <= r: return tree[p]
  push_down(p, cr - cl + 1)
  mid = cl + (cr - cl) // 2
  ans = 0
  if mid >= l: ans += query(l, r, p * 2, cl, mid)
  if mid < r: ans += query(l, r, p * 2 + 1, mid + 1, cr)
  return ans

arr =[0] + [int(x) for x in input().strip().split(' ')]

def build(p = 1, cl = 1, cr = n):
  if cr == cl: 
    global arr
    tree[p] = arr[cl]
    return
  mid = cl + (cr - cl) // 2
  build(p * 2, cl, mid)
  build(p * 2 + 1, mid + 1, cr)
  tree[p] = tree[p * 2] + tree[p * 2 + 1]

build()

# def build(arr):
#   for i, x in enumerate(arr):
#     update(i + 1, i + 1, x)

# build([int(x) for x in input().strip().split(' ')])

for _ in range(m):
  arr = [int(x) for x in input().strip().split(' ')]
  if arr[0] == 1:
    update(arr[1], arr[2], arr[3])
  else:
    print(query(arr[1], arr[2]))

by heyx0201 @ 2023-10-30 22:58:04

@dyegral 《照着网上文章写的》


by dyegral @ 2023-11-03 10:20:39

@heyx0201 嗯 有问题吗


by heyx0201 @ 2023-11-03 12:59:14

@dyegral 你就不怕网上的文章上面的代码不适合这道题吗


by heyx0201 @ 2023-11-03 13:02:23

@dyegral 你就不怕python因为常数太大导致TLE吗


|