feat(cses): range queries

;
This commit is contained in:
Barrett Ruth 2025-02-28 11:35:58 -05:00
parent 3b7cd11dc0
commit 60fc2a123c
39 changed files with 2044 additions and 19 deletions

55
cses/range-queries/rui Normal file
View file

@ -0,0 +1,55 @@
basically allows for answering queries of a range [l, r]
and updating values/ranges in O(lg(n))
so, for example, finding the minimum of elements in range [l, r]
can be answered in log(n) rather than r - l + 1
basically, you divide up the array into pieces:
this is the segtree
for each "segment" you store the answer for the query
[--------------- + x]
[------ + x][-------]
[--][-- + x][--][---]
[-][-][x][-][-][-]
usually way too advanced
its super powerful b/c you can, for example
find min/max/sum/gcd over ranges, while updating those values OR
updating a [l, r] range of values, all in O(lgn)
so, for example:
- sum from l to r
- update at index i
- increase indices [l, r] by x
^ all in log(n)
(pretty insane)
yes, but i alr knew it before
adv algos is tuff
say i update something to x
then i need to go back UP and update each segment
so it takes: O(lg(n)) time too
the problem: intervals don't cleanly overlap
so if i do sum[0:n/2+2]
i first get sum[0:n/2], then combine with sum[n/2:n/2+2]
the "height" is O(log(n)), so in worst-case you traverse down
the entire depth to combine the sum
last thing: updating a value