Editorial for Range Additions
Remember to use this editorial only when stuck, and not to 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.
Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Applying each query directly to every element in can take
, which is too slow.
Instead, use a difference array:
- To add
to every element in
, add
at position
.
- Subtract
at position
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 and the final reconstruction in
, so the total time
complexity is
.
Solution (Python)
import sys
data = list(map(int, sys.stdin.buffer.read().split()))
it = iter(data)
n = next(it)
q = next(it)
a = [next(it) for _ in range(n)]
diff = [0] * (n + 1)
for _ in range(q):
l = next(it) - 1
r = next(it)
x = next(it)
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))
sys.stdout.write(" ".join(ans) + "\n")
Comments