Editorial for Range Additions


Approach

Applying each query directly to every element in [l,r][l, r] can take O(nq)O(nq), which is too slow.

Instead, use a difference array:

  • To add xx to every element in [l,r][l, r], add xx at position ll.
  • Subtract xx at position r+1r + 1 if that position exists.
  • After processing all queries, take a prefix sum over the difference array to recover how much should be added to each index.

Then add that running total to the original array.

This processes all updates in O(q)O(q) and the final reconstruction in O(n)O(n), so the total time complexity is O(n+q)O(n + q).

Solution (Python)

Code 1
n, q = map(int, input().split())
a = list(map(int, input().split()))
diff = [0] * (n + 1)

for _ in range(q):
    l, r, x = map(int, input().split())
    l -= 1
    diff[l] += x
    if r < n:
        diff[r] -= x

cur = 0
ans = []
for i in range(n):
    cur += diff[i]
    ans.append(str(a[i] + cur))

print(" ".join(ans))

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.