Given an Array arr[] of positive integers of size n. We are required to perform following 3 queries on given array -
1) Given L and R, we have to find the sum of squares of all element lying in range [L,R]
2) Given L, R and X, we have to set all element lying in range [L,R] to X
3) Given L, R and X, we have to increment the value of all element lying in range [L,R] by X
Input Format : First line contains the number of test cases T
Next line contains two positive integers - N (Size of Array ) and Q (Number of queries to be asked).
The next line contains N integers of array
Each of the next Q lines contains the Q queries to be asked. Each line starts with a number, which indicates the type of query followed by required input arguments. Input format for all 3 queries will look like -
0 L R X : Set all numbers in Range [L, R] to "X"
1 L R X : ADD "X" to all numbers in Range [L, R]
2 L R : Return the sum of the squares of the numbers in Range {L, R]
Output Format : For each test case, output "Case <TestCaseNo>:” in first line and then output the sum of squares for each queries of type 2 in separate lines.
Input:
1
3 3
1 2 3
0 1 2 2
1 1 3 3
2 1 3
Output : Case 1:
86
Explanation : With 1st query (type 0), array elements from range [1,2] will set as 2. Updated array will become [2,2,3]
With 2nd query (type 1), array elements from range [1,3] will be incremented by 3. Updated array will become [5,5,6]
With 3rd query (type 2), Sum of Squares for range [1,3] will be 5^2+5^2+6^2 =86
Input:
1
4 5
1 2 3 4
2 1 4
0 3 4 1
2 1 4
1 3 4 1
2 1 4
Output : Case 1:
30
7
13
Optimized Solution
Sample Segment TreeWith the help of Segment tree with Lazy Propagation, we can perform all given queries in O(logn) time.
To know about how Segment Tree works, follow this link -https://www.geeksforgeeks.org/dsa/segment-tree-sum-of-given-range/
For this, we will create a segment tree with two variables - first one will store sum of squares in a range and other will store the sum of elements in the given range. (We will discuss this later why do we need two variables here). To update values in the given range, we will use lazy propagation technique.
For more information Regarding Lazy Propagation use link - https://www.geeksforgeeks.org/dsa/lazy-propagation-in-segment-tree/
Here if we have to set all numbers to X in a given range, then we can use this formula to update values for one particular node (which lies in given range) -
Updated Sum of squares = (R-L+1)*X*X
Updated Sum = (R-L+1)*X
(As there are R-L+1 elements present under that particular node which need to be set as X)
If we need to increment all values in the given range [L,R] with value X, we can use this formula to update values for one particular node (which lies in given range) -
Updated Sum of square = Sum of Square in range [L,R] + (R-L+1)*X*X + 2*X*(sum in range [L,R])
Updated Sum = Sum in Range [L,R] + (R-L+1)*X
(As there are R-L+1 elements present under that particular node which need to be incremented by X. Every node's value can be represented as : (Previous_val + X). To calculate new sum of squares for a root node, we can use this expression -
(Previous_val1+ x)^2 + (Previous_val2 + x)^2 + ..... (for all child nodes)
Above expression will simplify to Sum of Square in range [L,R] + (R-L+1)*X*X + 2*X*(sum in range [L,R])
Here you can see that we need sum of elements for calculation, hence we have stored this in our segment tree along with sum of squares to fasten our calculation.
How to Update using Lazy trees
Here you can see that we need 3 lazy trees -
1. For maintaining the set update
2. For maintaining the increment by X update
3. For maintaining the order of operations, in case multiple queries come for a single node
Now creating 3 lazy trees, will not be space effective. But we can solve this by creating 1 lazy tree (change, type) with two variables - one for maintaining the update value (X) and other for type (which update we need to do increment or set).
Now to handle order of multiple queries on single node, there can two possibilities -
1) First increment and then set query - in this case we actually don't need to increment the value, we can directly set the value to X. Because setting value of a node to X, before and after increment will remain same.
2) First set then increment query - Here effectively we are updating each node's value as : X (set query) + X (increment query). So we can keep our type of query as set and value of change (i.e. to which nodes value will be set) as (X_set + X_increment)
For ex - arr[]=[1,2,3,4] first set [3,4] with 2 then increment [3,4] with 1
array after set query = [1,2,2,2]
array after increment query = [1,2,3,3]
We can achieve this in one operation by setting the value for all given range nodes as :
(X_set + X_increment) = 2 + 1 = 3
Updated array = [1,2,3,3]
C++
// We will use 1 based indexing
// type 0 = Set
// type 1 = increment
#include<bits/stdc++.h>
using namespace std;
class segmenttree{
public:
int sum_of_squares;
int sum_of_element;
};
class lazytree{
public:
int change;
int type;
};
// Query On segment Tree
int query(segmenttree*tree,lazytree*lazy,int start,int end,int low,int high,int treeindex){
if(lazy[treeindex].change!=0){
int change=lazy[treeindex].change;
int type=lazy[treeindex].type;
if(lazy[treeindex].type==0){
tree[treeindex].sum_of_squares=(end-start+1)*change*change;
tree[treeindex].sum_of_element=(end-start+1)*change;
if(start!=end){
lazy[2*treeindex].change=change;
lazy[2*treeindex].type=type;
lazy[2*treeindex+1].change=change;
lazy[2*treeindex+1].type=type;
}
}
else{
tree[treeindex].sum_of_squares+=((end-start+1)*change*change)+(2*change*tree[treeindex].sum_of_element);
tree[treeindex].sum_of_element+=(end-start+1)*change;
if(start!=end){
if(lazy[2*treeindex].change==0 || lazy[2*treeindex].type==1){
lazy[2*treeindex].change+=change;
lazy[2*treeindex].type=type;
}else{
lazy[2*treeindex].change+=change;
}
if(lazy[2*treeindex+1].change==0 || lazy[2*treeindex+1].type==1){
lazy[2*treeindex+1].change+=change;
lazy[2*treeindex+1].type=type;
}else{
lazy[2*treeindex+1].change+=change;
}
}
}
lazy[treeindex].change=0;
}
if(start>high || end<low){
return 0;
}
if(start>=low && high>=end){
return tree[treeindex].sum_of_squares;
}
int mid=(start+end)/2;
int ans=query(tree,lazy,start,mid,low,high,2*treeindex);
int ans1=query(tree,lazy,mid+1,end,low,high,2*treeindex+1);
return ans+ans1;
}
// Update on Segment Tree
void update(int*arr,segmenttree*tree,lazytree*lazy,int start,int end,int low,int high,int change,int type,int treeindex){
if(lazy[treeindex].change!=0){
int change=lazy[treeindex].change;
int type=lazy[treeindex].type;
if(lazy[treeindex].type==0){
tree[treeindex].sum_of_squares=(end-start+1)*change*change;
tree[treeindex].sum_of_element=(end-start+1)*change;
if(start!=end){
lazy[2*treeindex].change=change;
lazy[2*treeindex].type=type;
lazy[2*treeindex+1].change=change;
lazy[2*treeindex+1].type=type;
}
}
else{
tree[treeindex].sum_of_squares+=((end-start+1)*change*change)+(2*change*tree[treeindex].sum_of_element);
tree[treeindex].sum_of_element+=(end-start+1)*change;
if(start!=end){
if(lazy[2*treeindex].change==0 || lazy[2*treeindex].type==1){
lazy[2*treeindex].change+=change;
lazy[2*treeindex].type=type;
}else{
lazy[2*treeindex].change+=change;
}
if(lazy[2*treeindex+1].change==0 || lazy[2*treeindex+1].type==1){
lazy[2*treeindex+1].change+=change;
lazy[2*treeindex+1].type=type;
}else{
lazy[2*treeindex+1].change+=change;
}
}
}
lazy[treeindex].change=0;
}
if(start>high || end<low){
return;
}
if(start>=low && high>=end){
if(type==0){
tree[treeindex].sum_of_squares=(end-start+1)*change*change;
tree[treeindex].sum_of_element=(end-start+1)*change;
if(start!=end){
lazy[2*treeindex].change=change;
lazy[2*treeindex].type=type;
lazy[2*treeindex+1].change=change;
lazy[2*treeindex+1].type=type;
}
}else{
tree[treeindex].sum_of_squares+=((end-start+1)*change*change)+(2*change*tree[treeindex].sum_of_element);
tree[treeindex].sum_of_element+=(end-start+1)*change;
if(start!=end){
if(lazy[2*treeindex].change==0 || lazy[2*treeindex].type==1){
lazy[2*treeindex].change+=change;
lazy[2*treeindex].type=type;
}else{
lazy[2*treeindex].change+=change;
}
if(lazy[2*treeindex+1].change==0 || lazy[2*treeindex+1].type==1){
lazy[2*treeindex+1].change+=change;
lazy[2*treeindex+1].type=type;
}else{
lazy[2*treeindex+1].change+=change;
}
}
}
return;
}
int mid=(start+end)/2;
update(arr,tree,lazy,start,mid,low,high,change,type,2*treeindex);
update(arr,tree,lazy,mid+1,end,low,high,change,type,2*treeindex+1);
tree[treeindex].sum_of_squares=tree[2*treeindex].sum_of_squares+tree[2*treeindex+1].sum_of_squares;
tree[treeindex].sum_of_element=tree[2*treeindex].sum_of_element+tree[2*treeindex+1].sum_of_element;
}
// creation of segment tree
void create(int*arr,segmenttree*tree,int start,int end,int treeindex){
if(start==end){
tree[treeindex].sum_of_squares=start*start;
tree[treeindex].sum_of_element=start;
return;
}
int mid=(start+end)/2;
create(arr,tree,start,mid,treeindex*2);
create(arr,tree,mid+1,end,2*treeindex+1);
tree[treeindex].sum_of_squares=tree[treeindex*2].sum_of_squares+tree[2*treeindex+1].sum_of_squares;
tree[treeindex].sum_of_element=tree[treeindex*2].sum_of_element+tree[2*treeindex+1].sum_of_element;
}
int main() {
int t;
cin>>t;
int case1=1;
while(t--){
cout<<"Case "<<case1++<<":"<<endl;
int n,q;
cin>>n>>q;
int*arr=new int[n+1];
for(int i=1;i<=n;i++){
cin>>arr[i];
}
segmenttree*tree=new segmenttree[2*n];
lazytree*lazy=new lazytree[2*n];
create(arr,tree,1,n,1);
while(q--){
int type;
cin>>type;
if(type==2){
int start,end;
cin>>start>>end;
cout<<query(tree,lazy,1,n,start,end,1)<<endl;
}else{
int start,end,change;
cin>>start>>end>>change;
update(arr,tree,lazy,1,n,start,end,change,type,1);
}
}
}
}
Java
// We will use 1 based indexing
// type 0 = Set
// type 1 = increment
import java.util.*;
// Define a class to hold information for each node in the segment tree
class SegmentTree {
public int sum_of_squares;
public int sum_of_element;
}
// Define a class to hold lazy update information for each node in the lazy tree
class LazyTree {
public int change;
public int type;
}
public class GFG {
// Query on the segment tree
static int query(SegmentTree[] tree, LazyTree[] lazy, int start, int end, int low, int high, int treeindex) {
// Check if there are pending updates for this node
if (lazy[treeindex].change != 0) {
int change = lazy[treeindex].change;
int type = lazy[treeindex].type;
// Apply the update based on the type (Set or Increment)
if (lazy[treeindex].type == 0) {
tree[treeindex].sum_of_squares = (end - start + 1) * change * change;
tree[treeindex].sum_of_element = (end - start + 1) * change;
if (start != end) {
// Propagate the update to child nodes
lazy[2 * treeindex].change = change;
lazy[2 * treeindex].type = type;
lazy[2 * treeindex + 1].change = change;
lazy[2 * treeindex + 1].type = type;
}
} else {
tree[treeindex].sum_of_squares += ((end - start + 1) * change * change) + (2 * change * tree[treeindex].sum_of_element);
tree[treeindex].sum_of_element += (end - start + 1) * change;
if (start != end) {
if (lazy[2 * treeindex].change == 0 || lazy[2 * treeindex].type == 1) {
lazy[2 * treeindex].change += change;
lazy[2 * treeindex].type = type;
} else {
lazy[2 * treeindex].change += change;
}
if (lazy[2 * treeindex + 1].change == 0 || lazy[2 * treeindex + 1].type == 1) {
lazy[2 * treeindex + 1].change += change;
lazy[2 * treeindex + 1].type = type;
} else {
lazy[2 * treeindex + 1].change += change;
}
}
}
// Reset the pending update after applying it
lazy[treeindex].change = 0;
}
// If the current node's range is completely outside the query range, return 0
if (start > high || end < low) {
return 0;
}
// If the current node's range is completely inside the query range, return the sum of squares
if (start >= low && high >= end) {
return tree[treeindex].sum_of_squares;
}
// Otherwise, query recursively in the left and right child nodes
int mid = (start + end) / 2;
int ans = query(tree, lazy, start, mid, low, high, 2 * treeindex);
int ans1 = query(tree, lazy, mid + 1, end, low, high, 2 * treeindex + 1);
return ans + ans1;
}
// Update on Segment Tree
static void update(int[] arr, SegmentTree[] tree, LazyTree[] lazy, int start, int end, int low, int high, int change, int type, int treeindex) {
// Check if there are pending updates for this node
if (lazy[treeindex].change != 0) {
int change1 = lazy[treeindex].change;
int type1 = lazy[treeindex].type;
// Apply the update based on the type (Set or Increment)
if (lazy[treeindex].type == 0) {
tree[treeindex].sum_of_squares = (end - start + 1) * change1 * change1;
tree[treeindex].sum_of_element = (end - start + 1) * change1;
if (start != end) {
// Propagate the update to child nodes
lazy[2 * treeindex].change = change1;
lazy[2 * treeindex].type = type1;
lazy[2 * treeindex + 1].change = change1;
lazy[2 * treeindex + 1].type = type1;
}
} else {
tree[treeindex].sum_of_squares += ((end - start + 1) * change1 * change1) + (2 * change1 * tree[treeindex].sum_of_element);
tree[treeindex].sum_of_element += (end - start + 1) * change1;
if (start != end) {
if (lazy[2 * treeindex].change == 0 || lazy[2 * treeindex].type == 1) {
lazy[2 * treeindex].change += change1;
lazy[2 * treeindex].type = type1;
} else {
lazy[2 * treeindex].change += change1;
}
if (lazy[2 * treeindex + 1].change == 0 || lazy[2 * treeindex + 1].type == 1) {
lazy[2 * treeindex + 1].change += change1;
lazy[2 * treeindex + 1].type = type1;
} else {
lazy[2 * treeindex + 1].change += change1;
}
}
}
// Reset the pending update after applying it
lazy[treeindex].change = 0;
}
// If the current node's range is completely outside the update range, return
if (start > high || end < low) {
return;
}
// If the current node's range is completely inside the update range, apply the update
if (start >= low && high >= end) {
if (type == 0) {
tree[treeindex].sum_of_squares = (end - start + 1) * change * change;
tree[treeindex].sum_of_element = (end - start + 1) * change;
if (start != end) {
// Propagate the update to child nodes
lazy[2 * treeindex].change = change;
lazy[2 * treeindex].type = type;
lazy[2 * treeindex + 1].change = change;
lazy[2 * treeindex + 1].type = type;
}
} else {
tree[treeindex].sum_of_squares += ((end - start + 1) * change * change) + (2 * change * tree[treeindex].sum_of_element);
tree[treeindex].sum_of_element += (end - start + 1) * change;
if (start != end) {
if (lazy[2 * treeindex].change == 0 || lazy[2 * treeindex].type == 1) {
lazy[2 * treeindex].change += change;
lazy[2 * treeindex].type = type;
} else {
lazy[2 * treeindex].change += change;
}
if (lazy[2 * treeindex + 1].change == 0 || lazy[2 * treeindex + 1].type == 1) {
lazy[2 * treeindex + 1].change += change;
lazy[2 * treeindex + 1].type = type;
} else {
lazy[2 * treeindex + 1].change += change;
}
}
}
return;
}
// Otherwise, update recursively in the left and right child nodes
int mid = (start + end) / 2;
update(arr, tree, lazy, start, mid, low, high, change, type, 2 * treeindex);
update(arr, tree, lazy, mid + 1, end, low, high, change, type, 2 * treeindex + 1);
// Update the current node's information based on the child nodes
tree[treeindex].sum_of_squares = tree[2 * treeindex].sum_of_squares + tree[2 * treeindex + 1].sum_of_squares;
tree[treeindex].sum_of_element = tree[2 * treeindex].sum_of_element + tree[2 * treeindex + 1].sum_of_element;
}
// Creation of segment tree
static void create(int[] arr, SegmentTree[] tree, int start, int end, int treeindex) {
// If the range consists of a single element, set the node's values accordingly
if (start == end) {
tree[treeindex].sum_of_squares = start * start;
tree[treeindex].sum_of_element = start;
return;
}
// Divide the range and recursively create child nodes
int mid = (start + end) / 2;
create(arr, tree, start, mid, treeindex * 2);
create(arr, tree, mid + 1, end, 2 * treeindex + 1);
// Update the current node's information based on the child nodes
tree[treeindex].sum_of_squares = tree[treeindex * 2].sum_of_squares + tree[2 * treeindex + 1].sum_of_squares;
tree[treeindex].sum_of_element = tree[treeindex * 2].sum_of_element + tree[2 * treeindex + 1].sum_of_element;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt(); // Read the number of test cases
int case1 = 1; // Initialize case counter
// Iterate through each test case
while (t-- > 0) {
System.out.println("Case " + case1 + ":");
int n = scanner.nextInt(); // Read the size of the array
int q = scanner.nextInt(); // Read the number of queries
int[] arr = new int[n + 1]; // Initialize the array with one-based indexing
// Read the elements of the array
for (int i = 1; i <= n; i++) {
arr[i] = scanner.nextInt();
}
SegmentTree[] tree = new SegmentTree[2 * n]; // Initialize the segment tree array
LazyTree[] lazy = new LazyTree[2 * n]; // Initialize the lazy tree array
// Create the segment tree
for (int i = 0; i < 2 * n; i++) {
tree[i] = new SegmentTree();
lazy[i] = new LazyTree();
}
create(arr, tree, 1, n, 1); // Build the segment tree
// Process the queries
while (q-- > 0) {
int type = scanner.nextInt(); // Read the query type
if (type == 2) {
int start = scanner.nextInt();
int end = scanner.nextInt();
System.out.println(query(tree, lazy, 1, n, start, end, 1)); // Execute query type 2
} else {
int start = scanner.nextInt();
int end = scanner.nextInt();
int change = scanner.nextInt();
update(arr, tree, lazy, 1, n, start, end, change, type, 1); // Execute query type 1
}
}
case1++; // Move to the next test case
}
}
}
// this code is written by arindam369
Python3
# We will use 1 based indexing
# type 0 = Set
# type 1 = increment
class SegmentTree:
def __init__(self, sum_of_squares, sum_of_element):
self.sum_of_squares = sum_of_squares
self.sum_of_element = sum_of_element
class LazyTree:
def __init__(self, change, type):
self.change = change
self.type = type
# Query On segment Tree
def query(tree, lazy, start, end, low, high, treeindex):
if lazy[treeindex].change != 0:
change = lazy[treeindex].change
type = lazy[treeindex].type
if lazy[treeindex].type == 0:
tree[treeindex].sum_of_squares = (
end - start + 1) * change * change
tree[treeindex].sum_of_element = (end - start + 1) * change
if start != end:
lazy[2 * treeindex].change = change
lazy[2 * treeindex].type = type
lazy[2 * treeindex + 1].change = change
lazy[2 * treeindex + 1].type = type
else:
tree[treeindex].sum_of_squares += ((end - start + 1) * change * change) + (
2 * change * tree[treeindex].sum_of_element)
tree[treeindex].sum_of_element += (end - start + 1) * change
if start != end:
if lazy[2 * treeindex].change == 0 or lazy[2 * treeindex].type == 1:
lazy[2 * treeindex].change += change
lazy[2 * treeindex].type = type
else:
lazy[2 * treeindex].change += change
if lazy[2 * treeindex + 1].change == 0 or lazy[2 * treeindex + 1].type == 1:
lazy[2 * treeindex + 1].change += change
lazy[2 * treeindex + 1].type = type
else:
lazy[2 * treeindex + 1].change += change
lazy[treeindex].change = 0
if start > high or end < low:
return 0
if start >= low and high >= end:
return tree[treeindex].sum_of_squares
mid = (start + end) // 2
ans = query(tree, lazy, start, mid, low, high, 2 * treeindex)
ans1 = query(tree, lazy, mid + 1, end, low, high, 2 * treeindex + 1)
return ans + ans1
# Update on Segment Tree
# Update on Segment Tree
def update(arr, tree, lazy, start, end, low, high, change, type, treeindex):
if lazy[treeindex].change != 0:
change = lazy[treeindex].change
type = lazy[treeindex].type
if lazy[treeindex].type == 0:
tree[treeindex].sum_of_squares = (
end - start + 1) * change * change
tree[treeindex].sum_of_element = (end - start + 1) * change
if start != end:
lazy[2 * treeindex].change = change
lazy[2 * treeindex].type = type
lazy[2 * treeindex + 1].change = change
lazy[2 * treeindex + 1].type = type
else:
tree[treeindex].sum_of_squares += ((end - start + 1) * change * change) + (
2 * change * tree[treeindex].sum_of_element)
tree[treeindex].sum_of_element += (end - start + 1) * change
if start != end:
if lazy[2 * treeindex].change == 0 or lazy[2 * treeindex].type == 1:
lazy[2 * treeindex].change += change
lazy[2 * treeindex].type = type
else:
lazy[2 * treeindex].change += change
if lazy[2 * treeindex + 1].change == 0 or lazy[2 * treeindex + 1].type == 1:
lazy[2 * treeindex + 1].change += change
lazy[2 * treeindex + 1].type = type
else:
lazy[2 * treeindex + 1].change += change
lazy[treeindex].change = 0
if start > high or end < low:
return
if start >= low and high >= end:
if type == 0:
tree[treeindex].sum_of_squares = (
end - start + 1) * change * change
tree[treeindex].sum_of_element = (end - start + 1) * change
if start != end:
lazy[2 * treeindex].change = change
lazy[2 * treeindex].type = type
lazy[2 * treeindex + 1].change = change
lazy[2 * treeindex + 1].type = type
else:
tree[treeindex].sum_of_squares += ((end - start + 1) * change * change) + (
2 * change * tree[treeindex].sum_of_element)
tree[treeindex].sum_of_element += (end - start + 1) * change
if start != end:
if lazy[2 * treeindex].change == 0 or lazy[2 * treeindex].type == 1:
lazy[2 * treeindex].change += change
lazy[2 * treeindex].type = type
else:
lazy[2 * treeindex].change += change
if lazy[2 * treeindex + 1].change == 0 or lazy[2 * treeindex + 1].type == 1:
lazy[2 * treeindex + 1].change += change
lazy[2 * treeindex + 1].type = type
else:
lazy[2 * treeindex + 1].change += change
return
mid = (start + end) // 2
update(arr, tree, lazy, start, mid, low, high, change, type, 2 * treeindex)
update(arr, tree, lazy, mid + 1, end, low,
high, change, type, 2 * treeindex + 1)
tree[treeindex].sum_of_squares = tree[2 * treeindex].sum_of_squares + \
tree[2 * treeindex + 1].sum_of_squares
tree[treeindex].sum_of_element = tree[2 * treeindex].sum_of_element + \
tree[2 * treeindex + 1].sum_of_element
# create Segment Tree
def create(arr, tree, lazy, start, end, treeindex):
if start == end:
tree[treeindex] = SegmentTree(arr[start] * arr[start], arr[start])
return
mid = (start + end) // 2
create(arr, tree, lazy, start, mid, 2 * treeindex)
create(arr, tree, lazy, mid + 1, end, 2 * treeindex + 1)
tree[treeindex] = SegmentTree(tree[2 * treeindex].sum_of_squares + tree[2 * treeindex + 1].sum_of_squares,
tree[2 * treeindex].sum_of_element + tree[2 * treeindex + 1].sum_of_element)
t = int(input())
case1 = 1
while t > 0:
print("Case {}:".format(case1))
case1 += 1
n, q = map(int, input().split())
arr = [0] * (n + 1)
for i in range(1, n + 1):
arr[i] = int(input())
tree = [0] * (2 * n)
lazy = [0] * (2 * n)
create(arr, tree, 1, n, 1)
while q > 0:
q -= 1
type = int(input())
if type == 2:
start, end = map(int, input().split())
print(query(tree, lazy, 1, n, start, end, 1))
else:
start, end, change = map(int, input().split())
update(arr, tree, lazy, 1, n, start, end, change, type, 1)
t -= 1
C#
using System;
class SegmentTree
{
public int SumOfSquares;
public int SumOfElement;
}
class LazyTree
{
public int Change;
public int Type;
}
class Program
{
// Query on Segment Tree
static int Query(SegmentTree[] tree, LazyTree[] lazy, int start, int end, int low, int high, int treeIndex)
{
if (lazy[treeIndex].Change != 0)
{
int change = lazy[treeIndex].Change;
int type = lazy[treeIndex].Type;
if (lazy[treeIndex].Type == 0)
{
tree[treeIndex].SumOfSquares = (end - start + 1) * change * change;
tree[treeIndex].SumOfElement = (end - start + 1) * change;
if (start != end)
{
lazy[2 * treeIndex].Change = change;
lazy[2 * treeIndex].Type = type;
lazy[2 * treeIndex + 1].Change = change;
lazy[2 * treeIndex + 1].Type = type;
}
}
else
{
tree[treeIndex].SumOfSquares += ((end - start + 1) * change * change) + (2 * change * tree[treeIndex].SumOfElement);
tree[treeIndex].SumOfElement += (end - start + 1) * change;
if (start != end)
{
if (lazy[2 * treeIndex].Change == 0 || lazy[2 * treeIndex].Type == 1)
{
lazy[2 * treeIndex].Change += change;
lazy[2 * treeIndex].Type = type;
}
else
{
lazy[2 * treeIndex].Change += change;
}
if (lazy[2 * treeIndex + 1].Change == 0 || lazy[2 * treeIndex + 1].Type == 1)
{
lazy[2 * treeIndex + 1].Change += change;
lazy[2 * treeIndex + 1].Type = type;
}
else
{
lazy[2 * treeIndex + 1].Change += change;
}
}
}
lazy[treeIndex].Change = 0;
}
if (start > high || end < low)
{
return 0;
}
if (start >= low && high >= end)
{
return tree[treeIndex].SumOfSquares;
}
int mid = (start + end) / 2;
int ans = Query(tree, lazy, start, mid, low, high, 2 * treeIndex);
int ans1 = Query(tree, lazy, mid + 1, end, low, high, 2 * treeIndex + 1);
return ans + ans1;
}
// Update on Segment Tree
static void Update(int[] arr, SegmentTree[] tree, LazyTree[] lazy, int start, int end, int low, int high, int change, int type, int treeIndex)
{
if (lazy[treeIndex].Change != 0)
{
int lazyChange = lazy[treeIndex].Change;
int lazyType = lazy[treeIndex].Type;
if (lazy[treeIndex].Type == 0)
{
tree[treeIndex].SumOfSquares = (end - start + 1) * lazyChange * lazyChange;
tree[treeIndex].SumOfElement = (end - start + 1) * lazyChange;
if (start != end)
{
lazy[2 * treeIndex].Change = lazyChange;
lazy[2 * treeIndex].Type = lazyType;
lazy[2 * treeIndex + 1].Change = lazyChange;
lazy[2 * treeIndex + 1].Type = lazyType;
}
}
else
{
tree[treeIndex].SumOfSquares += ((end - start + 1) * lazyChange * lazyChange) + (2 * lazyChange * tree[treeIndex].SumOfElement);
tree[treeIndex].SumOfElement += (end - start + 1) * lazyChange;
if (start != end)
{
if (lazy[2 * treeIndex].Change == 0 || lazy[2 * treeIndex].Type == 1)
{
lazy[2 * treeIndex].Change += lazyChange;
lazy[2 * treeIndex].Type = lazyType;
}
else
{
lazy[2 * treeIndex].Change += lazyChange;
}
if (lazy[2 * treeIndex + 1].Change == 0 || lazy[2 * treeIndex + 1].Type == 1)
{
lazy[2 * treeIndex + 1].Change += lazyChange;
lazy[2 * treeIndex + 1].Type = lazyType;
}
else
{
lazy[2 * treeIndex + 1].Change += lazyChange;
}
}
}
lazy[treeIndex].Change = 0;
}
if (start > high || end < low)
{
return;
}
if (start >= low && high >= end)
{
if (type == 0)
{
tree[treeIndex].SumOfSquares = (end - start + 1) * change * change;
tree[treeIndex].SumOfElement = (end - start + 1) * change;
if (start != end)
{
lazy[2 * treeIndex].Change = change;
lazy[2 * treeIndex].Type = type;
lazy[2 * treeIndex + 1].Change = change;
lazy[2 * treeIndex + 1].Type = type;
}
}
else
{
tree[treeIndex].SumOfSquares += ((end - start + 1) * change * change) + (2 * change * tree[treeIndex].SumOfElement);
tree[treeIndex].SumOfElement += (end - start + 1) * change;
if (start != end)
{
if (lazy[2 * treeIndex].Change == 0 || lazy[2 * treeIndex].Type == 1)
{
lazy[2 * treeIndex].Change += change;
lazy[2 * treeIndex].Type = type;
}
else
{
lazy[2 * treeIndex].Change += change;
}
if (lazy[2 * treeIndex + 1].Change == 0 || lazy[2 * treeIndex + 1].Type == 1)
{
lazy[2 * treeIndex + 1].Change += change;
lazy[2 * treeIndex + 1].Type = type;
}
else
{
lazy[2 * treeIndex + 1].Change += change;
}
}
}
return;
}
int mid = (start + end) / 2;
Update(arr, tree, lazy, start, mid, low, high, change, type, 2 * treeIndex);
Update(arr, tree, lazy, mid + 1, end, low, high, change, type, 2 * treeIndex + 1);
tree[treeIndex].SumOfSquares = tree[2 * treeIndex].SumOfSquares + tree[2 * treeIndex + 1].SumOfSquares;
tree[treeIndex].SumOfElement = tree[2 * treeIndex].SumOfElement + tree[2 * treeIndex + 1].SumOfElement;
}
// Creation of Segment Tree
static void Create(int[] arr, SegmentTree[] tree, int start, int end, int treeIndex)
{
if (start == end)
{
tree[treeIndex].SumOfSquares = start * start;
tree[treeIndex].SumOfElement = start;
return;
}
int mid = (start + end) / 2;
Create(arr, tree, start, mid, treeIndex * 2);
Create(arr, tree, mid + 1, end, 2 * treeIndex + 1);
tree[treeIndex].SumOfSquares = tree[treeIndex * 2].SumOfSquares + tree[2 * treeIndex + 1].SumOfSquares;
tree[treeIndex].SumOfElement = tree[treeIndex * 2].SumOfElement + tree[2 * treeIndex + 1].SumOfElement;
}
static void Main()
{
int t;
if (int.TryParse(Console.ReadLine(), out t))
{
int case1 = 1;
while (t-- > 0)
{
Console.WriteLine($"Case {case1++}:");
string[] input = Console.ReadLine()?.Split() ?? Array.Empty<string>();
if (input.Length >= 2)
{
int n;
int q;
if (int.TryParse(input[0], out n) && int.TryParse(input[1], out q))
{
int[] arr = new int[n + 1];
input = Console.ReadLine()?.Split() ?? Array.Empty<string>();
for (int i = 1; i <= n; i++)
{
if (int.TryParse(input[i - 1], out arr[i]) == false)
{
Console.WriteLine("Invalid input for array element.");
return;
}
}
SegmentTree[] tree = new SegmentTree[2 * n];
LazyTree[] lazy = new LazyTree[2 * n];
Create(arr, tree, 1, n, 1);
while (q-- > 0)
{
int type;
if (int.TryParse(Console.ReadLine(), out type))
{
if (type == 2)
{
input = Console.ReadLine()?.Split() ?? Array.Empty<string>();
if (input.Length >= 2)
{
int start;
int end;
if (int.TryParse(input[0], out start) && int.TryParse(input[1], out end))
{
Console.WriteLine(Query(tree, lazy, 1, n, start, end, 1));
}
else
{
Console.WriteLine("Invalid input for query.");
return;
}
}
}
else
{
input = Console.ReadLine()?.Split() ?? Array.Empty<string>();
if (input.Length >= 3)
{
int start;
int end;
int change;
if (int.TryParse(input[0], out start) && int.TryParse(input[1], out end) && int.TryParse(input[2], out change))
{
Update(arr, tree, lazy, 1, n, start, end, change, type, 1);
}
else
{
Console.WriteLine("Invalid input for update.");
return;
}
}
}
}
}
}
else
{
Console.WriteLine("Invalid input for n and q.");
return;
}
}
}
}
}
}
JavaScript
// We will use 1 based indexing
// type 0 = Set
// type 1 = increment
class SegmentTree {
constructor() {
this.sum_of_squares = 0;
this.sum_of_element = 0;
}
}
class LazyTree {
constructor() {
this.change = 0;
this.type = 0;
}
}
function query(tree, lazy, start, end, low, high, treeindex) {
if (lazy[treeindex].change !== 0) {
const change = lazy[treeindex].change;
const type = lazy[treeindex].type;
if (lazy[treeindex].type === 0) {
tree[treeindex].sum_of_squares = (end - start + 1) * change * change;
tree[treeindex].sum_of_element = (end - start + 1) * change;
if (start !== end) {
lazy[2 * treeindex].change = change;
lazy[2 * treeindex].type = type;
lazy[2 * treeindex + 1].change = change;
lazy[2 * treeindex + 1].type = type;
}
} else {
tree[treeindex].sum_of_squares += ((end - start + 1) * change * change) + (2 * change * tree[treeindex].sum_of_element);
tree[treeindex].sum_of_element += (end - start + 1) * change;
if (start !== end) {
if (lazy[2 * treeindex].change === 0 || lazy[2 * treeindex].type === 1) {
lazy[2 * treeindex].change += change;
lazy[2 * treeindex].type = type;
} else {
lazy[2 * treeindex].change += change;
}
if (lazy[2 * treeindex + 1].change === 0 || lazy[2 * treeindex + 1].type === 1) {
lazy[2 * treeindex + 1].change += change;
lazy[2 * treeindex + 1].type = type;
} else {
lazy[2 * treeindex + 1].change += change;
}
}
}
lazy[treeindex].change = 0;
}
if (start > high || end < low) {
return 0;
}
if (start >= low && high >= end) {
return tree[treeindex].sum_of_squares;
}
const mid = Math.floor((start + end) / 2);
const ans = query(tree, lazy, start, mid, low, high, 2 * treeindex);
const ans1 = query(tree, lazy, mid + 1, end, low, high, 2 * treeindex + 1);
return ans + ans1;
}
function update(arr, tree, lazy, start, end, low, high, change, type, treeindex) {
if (lazy[treeindex].change !== 0) {
const change1 = lazy[treeindex].change;
const type1 = lazy[treeindex].type;
if (lazy[treeindex].type === 0) {
tree[treeindex].sum_of_squares = (end - start + 1) * change1 * change1;
tree[treeindex].sum_of_element = (end - start + 1) * change1;
if (start !== end) {
lazy[2 * treeindex].change = change1;
lazy[2 * treeindex].type = type1;
lazy[2 * treeindex + 1].change = change1;
lazy[2 * treeindex + 1].type = type1;
}
} else {
tree[treeindex].sum_of_squares += ((end - start + 1) * change1 * change1) + (2 * change1 * tree[treeindex].sum_of_element);
tree[treeindex].sum_of_element += (end - start + 1) * change1;
if (start !== end) {
if (lazy[2 * treeindex].change === 0 || lazy[2 * treeindex].type === 1) {
lazy[2 * treeindex].change += change1;
lazy[2 * treeindex].type = type1;
} else {
lazy[2 * treeindex].change += change1;
}
if (lazy[2 * treeindex + 1].change === 0 || lazy[2 * treeindex + 1].type === 1) {
lazy[2 * treeindex + 1].change += change1;
lazy[2 * treeindex + 1].type = type1;
} else {
lazy[2 * treeindex + 1].change += change1;
}
}
}
lazy[treeindex].change = 0;
}
if (start > high || end < low) {
return;
}
if (start >= low && high >= end) {
if (type === 0) {
tree[treeindex].sum_of_squares = (end - start + 1) * change * change;
tree[treeindex].sum_of_element = (end - start + 1) * change;
if (start !== end) {
lazy[2 * treeindex].change = change;
lazy[2 * treeindex].type = type;
lazy[2 * treeindex + 1].change = change;
lazy[2 * treeindex + 1].type = type;
}
} else {
tree[treeindex].sum_of_squares += ((end - start + 1) * change * change) + (2 * change * tree[treeindex].sum_of_element);
tree[treeindex].sum_of_element += (end - start + 1) * change;
if (start !== end) {
if (lazy[2 * treeindex].change === 0 || lazy[2 * treeindex].type === 1) {
lazy[2 * treeindex].change += change;
lazy[2 * treeindex].type = type;
} else {
lazy[2 * treeindex].change += change;
}
if (lazy[2 * treeindex + 1].change === 0 || lazy[2 * treeindex + 1].type === 1) {
lazy[2 * treeindex + 1].change += change;
lazy[2 * treeindex + 1].type = type;
} else {
lazy[2 * treeindex + 1].change += change;
}
}
}
return;
}
const mid = Math.floor((start + end) / 2);
update(arr, tree, lazy, start, mid, low, high, change, type, 2 * treeindex);
update(arr, tree, lazy, mid + 1, end, low, high, change, type, 2 * treeindex + 1);
tree[treeindex].sum_of_squares = tree[2 * treeindex].sum_of_squares + tree[2 * treeindex + 1].sum_of_squares;
tree[treeindex].sum_of_element = tree[2 * treeindex].sum_of_element + tree[2 * treeindex + 1].sum_of_element;
}
function create(arr, tree, start, end, treeindex) {
if (start === end) {
tree[treeindex].sum_of_squares = start * start;
tree[treeindex].sum_of_element = start;
return;
}
const mid = Math.floor((start + end) / 2);
create(arr, tree, start, mid, treeindex * 2);
create(arr, tree, mid + 1, end, 2 * treeindex + 1);
tree[treeindex].sum_of_squares = tree[treeindex * 2].sum_of_squares + tree[2 * treeindex + 1].sum_of_squares;
tree[treeindex].sum_of_element = tree[treeindex * 2].sum_of_element + tree[2 * treeindex + 1].sum_of_element;
}
function main() {
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let t;
let case1 = 1;
rl.on('line', (input) => {
if (!t) {
t = parseInt(input);
} else {
if (case1 <= t) {
console.log(`Case ${case1}:`);
const inputs = input.split(' ').map(Number);
const n = inputs[0];
const q = inputs[1];
const arr = [0, ...Array.from({ length: n }, (_, i) => parseInt(rl.readline()))];
const tree = new Array(2 * n);
const lazy = new Array(2 * n);
for (let i = 0; i < 2 * n; i++) {
tree[i] = new SegmentTree();
lazy[i] = new LazyTree();
}
create(arr, tree, 1, n, 1);
for (let i = 0; i < q; i++) {
const queryType = parseInt(rl.readline());
if (queryType === 2) {
const [start, end] = rl.readline().split(' ').map(Number);
console.log(query(tree, lazy, 1, n, start, end, 1));
} else {
const [start, end, change] = rl.readline().split(' ').map(Number);
update(arr, tree, lazy, 1, n, start, end, change, queryType, 1);
}
}
case1++;
}
if (case1 > t) {
rl.close();
}
}
});
}
main();
Time Complexity:
Time Complexity for tree construction is O(n). There are total 2n-1 nodes, and value of every node is calculated only once in tree construction.
Time complexity to query is O(Logn).
The time complexity of update is also O(Logn).
Space Complexity : O(2*N) .
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem