![]() |
VOOZH | about |
Given an array of size N filled with all 1s, the task is to answer Q queries, where the queries can be one of the two types:
Type 1 (1, L, R, X): Multiply all elements on the segment from L to R−1 by X, and
Type 2 (2, L, R): Find the sum on the segment from L to R−1.
Examples:
Input: N = 5, Q = 6, queries[] = {
{1, 0, 3, 3},
{2, 1, 2},
{1, 1, 4, 4},
{2, 1, 3},
{2, 1, 4},
{2, 3, 5}}
Output: 3 24 28 5
Explanation:
- Initially the array is {1, 1, 1, 1, 1}
- First query is to multiply segment from index 0 to 2 by 3, so after first query the array is {3, 3, 3, 1, 1}.
- Second query is to print the sum of segment from index 1 to 1, so the sum = 3.
- Third query is to multiply segment from index 1 to 3 by 4, so after third query is {3, 12, 12, 4, 1, 1}.
- Fourth query is to print the sum of segment from index 1 to 2, so the sum = 12 + 12 = 24.
- Fifth query is to print the sum of segment from index 1 to 3, so the sum = 12 + 12 + 4 = 28.
- Sixth query is to print the sum of segment from index 3 to 4, so the sum = 4 + 1 = 5.
Input: N = 2, Q = 2, queries[] = {
{1, 0, 1, 1000000},
{2 0 2}}
Output: 1000001
Approach: To solve the problem, follow the below idea
The idea is to use a segment tree data structure with lazy propagation to efficiently process the queries. The segment tree is built such that each node stores the sum of its corresponding segment of the array. When an update query is performed, instead of immediately updating all the elements in the range, the update is postponed and stored in a separate array called lazy. The pending updates are applied only when they are needed, i.e., when a sum query is performed on a node or its descendants.
Step-by-step algorithm:
Below is the implementation of the algorithm:
3 24 28 5
Time Complexity: O(NlogN + MlogN), where N is the array size and M is the number of operations.
Auxiliary Space: O(N) for the segment tree and lazy propagation arrays.