Open In App

Queries to calculate sum of squares of array elements over range of indices [L, R] with updates

Last Updated : 03 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 Tree

With 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/segment-tree-set-1-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/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();


Output


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) .



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads