Editorial for Range Additions
Use this editorial only when stuck, and do not copy-paste code from it.
Please be respectful to the problem author and editorialist. Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Applying each query directly to every element in [l,r] can take O(nq), which is too slow.
Instead, use a difference array:
- To add x to every element in [l,r], add x at position l.
- Subtract x at position r+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) and the final reconstruction in O(n), so the total time complexity is O(n+q).
Solution (Python)
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.