Given an array arr[] of size N. There are two types of operations:
- Update(l, r, x) : Increment the a[i] (l <= i <= r) with value x.
- Query(l, r) : Find the maximum value in the array in a range l to r (both are included).
Examples:
Input: arr[] = {1, 2, 3, 4, 5}
Update(0, 3, 4)
Query(1, 4)
Output: 8
After applying the update operation
in the given range with given value array becomes {5, 6, 7, 8, 5}.
Then the maximum value in the range 1 to 4 is 8.
Input: arr[] = {1, 2, 3, 4, 5}
Update(0, 0, 10)
Query(0, 4)
Output: 11
Approach: A detailed explanation about the lazy propagation in the segment tree is explained previously. The only thing that needed to change in the question is to return a maximum value between two child nodes when the parent node query is called. See the code for better understanding.
Below is the implementation of the above approach:
Another Version : Above was implementation in which while performing range update queries we add difference to each node in segment tree,
Another approach could be to set all values in range with given value.
Below is the implementation of the approach :
Outputupdating range from 0 to 3 with value : 0
updating range from 2 to 3 with value : 2
updating range from 0 to 2 with value : 10
sum in range : 1 to 2 : 20
The implementation class has following members :
- n: The size of the input array.
- MYSIZE: The size of the Segment Tree array.
- tree: The Segment Tree array used to store the sum of the values of the input array over a range of indices.
- lazy: The lazy array used to store the updates to be propagated to the Segment Tree.
- stamp: The stamp array is used to store the timestamp of the update.
- pending: A boolean array to keep track of pending updates in the Segment Tree.
- arr: The input array of integers.
The class has the following member functions:
- init(int n): Initializes the data members of the class with the input size n.
- post_init(): Constructs the Segment Tree using the input array.
- updateRangeUtil(int si, int ss, int se, int us, int ue, int diff,int stamp_value): A utility function that updates the Segment Tree using lazy propagation technique.
- updateRange(int us, int ue, int diff): A function that updates the input array over a range of indices.
- update(int us, int ue, int diff): A function that updates the input array over a range of indices.
- getSumUtil(int ss, int se, int qs, int qe, int si): A utility function that returns the sum of the values of the input array over a range of indices.
- getSum(int qs, int qe): A function that returns the sum of the values of the input array over a range of indices.
- query(int qs, int qe): A function that returns the sum of the values of the input array over a range of indices.
Related Topic: Segment Tree