Looks like there is only one good article about lazy propagation in Segment Tree on entire internet and it is: http://www.spoj.pl/forum/viewtopic.php?f=27&t=8296
I understood the concept of updating only query node and marking its child. But my question is what if I query child node first and parent node later.
In this tree (along with location in array of heap )
0->[0 9]
1->[0 4] 2->[5 9]
3->[0 2] 4->[3 4] 5->[5 7] 6->[8 9]
.....................................
First query, if I update [0 4], its data will be changed and its child will be flagged. Second query, is read state of segment [0 9].
Here I face the issue. My segment tree implementation is such that value of each node is sum of its left and right child. So when I update node's value I've to update it's all parents. To fix logical issue, now I'm updating all parent of node (till it reaches root of tree). But this is taking performance toll and my whole purpose of using segment tree for fast batch update is getting killed.
Can anyone please explain, where I'm going wrong in using segment tree?
I will contrast lazy update operation to a normal update operation and how this changes query operation.
In a normal single update operation you update the root of a tree and then recursively update only the needed part of the tree (thus giving you a
O(log(n))
speed). If you will try to use the same logic for a range updates, you can see how it can deteriorate toO(n)
(consider very broad ranges and see that you will mostly need to update both parts of the tree).So in order to overcome this
O(n)
idea is to update the tree only when you really need it (query/update on the segment which was previously updated, thus making your updates lazy). So here is how it works:Here is an example of update and query (solving maximum range query). For a full code - check this article.
and query: