Hi everybody!
I am solving problem that need addition on a segment and getting sum and minimum on a segment. I have some problem with lazy propagation.
Can you share your code with Segment tree. Preferably recursively)
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 151 |
Hi everybody!
I am solving problem that need addition on a segment and getting sum and minimum on a segment. I have some problem with lazy propagation.
Can you share your code with Segment tree. Preferably recursively)
Name |
---|
Auto comment: topic has been translated by jaguar1996 (original revision, translated revision, compare)
In every node of the segment tree put two values: sum of range and minimum of range.
Everytime you update a node with sum s and minimum x, update these values. If the range is [l, r], then s = s + (r - l + 1)·v (where v is the value you are adding to the range). Minimum should be updated too: x = x + v
Propagate the v value to the children as always.
hello,i have a stupid question about segment tree lazy propagation..why we need to Propagate the v ((where v is the value you are adding to the range)value to its children when we do a update function, can not we Propagate the v value to the children when we do query function(or say it just do what we really want to do?) can you explain it more details,becasue it confused me sevearl days to think this question...thanks in advance...
When applying lazy propagation, every node on the segment tree has some "lazy" values. In this case, the lazy values is the sum we are adding to a range.
If you update a node that represents a range [l, r], you must update the lazy values of its children, but nothing more, there's no need to go down to the leaves of the tree. We use these lazy values to update the nodes when needed.
So, when we attend another query, if we go to a node whose lazy value is on (it needs to be updated), we update the node and push the lazy value to the children (unless the node is a leaf)
This way, the complexity of the queries will be O(logn)
Here's mine. It is only addition and minimum, but can be easily edited to support sum operation.
You can watch this video: https://www.youtube.com/watch?v=Tr-xEGoByFQ
I code a segment tree and talk about how lazy propagation works. I don't remember if I talk about sum, but it is not very complicated if you can get a good understanding of lazy propagation.
This problem is kind of similar. You can see the editorial and others code too.