lovingly prepared by Conrad Soon for NUS OrcaCode © 2024
Motivation
In this talk:
Prefix sum (apparently covered by Shawn)
Variations on a theme
Prefix sum problems
Reference implementation
# function to preprocess the input array and compute prefix sums
def prefix_sums(arr):
n = len(arr)
prefix = [0] * (n + 1)
for i in range(1, n + 1):
prefix[i] = prefix[i - 1] + arr[i - 1]
return prefix
# function to handle queries using the prefix sum array
def range_sum_query(prefix, a, b):
return prefix[b] - prefix[a - 1]
# read input values
n, q = map(int, input().split()) # number of elements and queries
arr = list(map(int, input().split())) # array of elements
# compute prefix sums
prefix = prefix_sums(arr)
# process each query and print the sum of values in the given range
for _ in range(q):
a, b = map(int, input().split())
print(range_sum_query(prefix, a, b))
Recap:
Segment trees
Let’s think of how to break up the calculation
TL:DR; Please draw a pretty picture
Let’s phrase it algorithmically
Let’s phrase it algorithmically
Back to the drawing board.
Claim: range queries in O(log n), NOT O(n)!
Wait, how do we calculate the blocks in the first place?
Claim: updates are in log(n) now too!
Claim: updates are in log(n) now too!
Reference implementation
Recap
Lazy propagation
Lazy propagation
Let’s phrase it algorithmically
Back to the drawing board.
Claim: range update is log(n)
Recap
Variations on a theme
Why is it not O(n) and not O(log n)?
Read more for lazy propagation
(Bonus 1) Square root decomposition
(Bonus 2) Sparse table
LCA
LCAs: RMQs in Disguise
LCAs: RMQs in Disguise
This is what I procrastinated on to prepare this talk
For the grouptheorypilled mathcels: a summary
Read more