Given an array arr[] of size N and a 2D array Q[][], consisting of queries of the following two types:
- 1 X Val: Update arr[X] = Val.
- 2 L R: Find the sum of array elements with alternating signs in the range [L, R].
Examples:
Input: arr[] = { 1, 2, 3, 4 }, Q[][] = { { 2, 0, 3 }, { 1, 1, 5 }, { 2, 1, 2 } }Â
Output:-2 2Â
Explanation:Â
Query1: Print (arr[0] – arr[1] + arr[2] – arr[3]) = 1 – 2 + 3 – 4 = -2Â
Query2: Updating arr[1] to 5 modifies arr[] to { 1, 5, 3, 4 }Â
Query3: Print (arr[1] – arr[2]) = 5 – 3 = 2Input: arr[] = { 4, 2, 6, 1, 8, 9, 2}, Q = { { 2, 1, 4 }, { 1, 3, 4 }, { 2, 0, 3 } }Â
Output: -11 5
Approach: The problem can be solved using Segment Tree. The idea is to traverse the array and check if the index of the array element is negative then multiply the array elements by -1. Follow the steps below to solve the problem:
- Traverse the array arr[] using variable i and check if the index i is odd or not. If found to be true, then update arr[i] = -Val.
- For query of type 1, X, Val, check if X is even or not. If found to be true, then update arr[X] = Val using segment tree.
- Otherwise, update arr[X] = -Val using segment tree.
- For query of type 2 L R:, check if L is even or not. If found to be true, then print the sum of array elements in the range [L, R] using the segment tree.
- Otherwise, find the sum of array elements in the range [L, R] using segment tree and print the obtained sum multiplying by -1.
Below is the implementation of the above approach :
C++
// C++Â program to implement// the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to build the segment treevoid build(int tree[], int arr[], int start,           int end, int index){Â
    // If current node is a leaf node    // of the segment tree    if (start == end) {Â
        if (start % 2 == 0) {Â
            // Update tree[index]            tree[index] = arr[start];        }Â
        else {Â
            // Update tree[index]            tree[index] = -arr[start];        }        return;    }Â
    // Divide the segment tree    int mid = start + (end - start) / 2;Â
    // Update on L segment tree    build(tree, arr, start, mid,          2 * index + 1);Â
    // Update on R segment tree    build(tree, arr, mid + 1, end,          2 * index + 2);Â
    // Find the sum from L subtree    // and R subtree    tree[index] = tree[2 * index + 1] + tree[2 * index + 2];}Â
// Function to update elements at index pos// by val in the segment treevoid update(int tree[], int index, int start,            int end, int pos, int val){Â
    // If current node is a leaf node    if (start == end) {Â
        // If current index is even        if (start % 2 == 0) {Â
            // Update tree[index]            tree[index] = val;        }Â
        else {Â
            // Update tree[index]            tree[index] = -val;        }        return;    }Â
    // Divide the segment tree elements    // into L and R subtree    int mid = start + (end - start) / 2;Â
    // If element lies in L subtree    if (mid >= pos) {Â
        update(tree, 2 * index + 1, start,               mid, pos, val);    }    else {        update(tree, 2 * index + 2, mid + 1,               end, pos, val);    }Â
    // Update tree[index]    tree[index]        = tree[2 * index + 1] + tree[2 * index + 2];}Â
// Function to find the sum of array elements// in the range [L, R]int FindSum(int tree[], int start, int end,            int L, int R, int index){Â
    // If start and end not lies in    // the range [L, R]    if (L > end || R < start) {        return 0;    }Â
    // If start and end comleately lies    // in the range [L, R]    if (L <= start && R >= end) {Â
        return tree[index];    }    int mid = start + (end - start) / 2;Â
    // Stores sum from left subtree    int X = FindSum(tree, start, mid, L,                    R, 2 * index + 1);Â
    // Stores sum from right subtree    int Y = FindSum(tree, mid + 1, end, L,                    R, 2 * index + 2);Â
    return X + Y;}Â
int main(){Â
    int arr[] = { 1, 2, 3, 4 };    int N = sizeof(arr) / sizeof(arr[0]);    int tree[4 * N + 5] = { 0 };    build(tree, arr, 0, N - 1, 0);Â
    int Q[][3] = { { 2, 0, 3 }, { 1, 1, 5 }, { 2, 1, 2 } };Â
    int cntQuey = 3;    for (int i = 0; i < cntQuey; i++) {Â
        if (Q[i][0] == 1) {Â
            update(tree, 0, 0, N - 1,                   Q[i][1], Q[i][2]);        }Â
        else {Â
            if (Q[i][1] % 2 == 0) {Â
                cout << FindSum(tree, 0, N - 1,                                Q[i][1], Q[i][2], 0)                     << " ";            }            else {Â
                cout << -FindSum(tree, 0, N - 1,                                 Q[i][1], Q[i][2], 0)                     << " ";            }        }    }} |
Java
// Java program to implement// the above approachimport java.util.*;  class GFG{  // Function to build the segment treestatic void build(int tree[], int arr[], int start,           int end, int index){Â
    // If current node is a leaf node    // of the segment tree    if (start == end) {Â
        if (start % 2 == 0) {Â
            // Update tree[index]            tree[index] = arr[start];        }Â
        else {Â
            // Update tree[index]            tree[index] = -arr[start];        }        return;    }Â
    // Divide the segment tree    int mid = start + (end - start) / 2;Â
    // Update on L segment tree    build(tree, arr, start, mid,          2 * index + 1);Â
    // Update on R segment tree    build(tree, arr, mid + 1, end,          2 * index + 2);Â
    // Find the sum from L subtree    // and R subtree    tree[index] = tree[2 * index + 1] + tree[2 * index + 2];}Â
// Function to update elements at index pos// by val in the segment treestatic void update(int tree[], int index, int start,            int end, int pos, int val){Â
    // If current node is a leaf node    if (start == end) {Â
        // If current index is even        if (start % 2 == 0) {Â
            // Update tree[index]            tree[index] = val;        }Â
        else {Â
            // Update tree[index]            tree[index] = -val;        }        return;    }Â
    // Divide the segment tree elements    // into L and R subtree    int mid = start + (end - start) / 2;Â
    // If element lies in L subtree    if (mid >= pos)    {        update(tree, 2 * index + 1, start,               mid, pos, val);    }    else    {        update(tree, 2 * index + 2, mid + 1,               end, pos, val);    }Â
    // Update tree[index]    tree[index]        = tree[2 * index + 1] + tree[2 * index + 2];}Â
// Function to find the sum of array elements// in the range [L, R]static int FindSum(int tree[], int start, int end,            int L, int R, int index){Â
    // If start and end not lies in    // the range [L, R]    if (L > end || R < start)     {        return 0;    }Â
    // If start and end comleately lies    // in the range [L, R]    if (L <= start && R >= end)     {        return tree[index];    }    int mid = start + (end - start) / 2;Â
    // Stores sum from left subtree    int X = FindSum(tree, start, mid, L,                    R, 2 * index + 1);Â
    // Stores sum from right subtree    int Y = FindSum(tree, mid + 1, end, L,                    R, 2 * index + 2);    return X + Y;}   // Driver Codepublic static void main(String[] args){    int arr[] = { 1, 2, 3, 4 };    int N = arr.length;    int tree[] = new int[4 * N + 5];    Arrays.fill(tree, 0);    build(tree, arr, 0, N - 1, 0);    int Q[][] = { { 2, 0, 3 }, { 1, 1, 5 }, { 2, 1, 2 } };    int cntQuey = 3;    for (int i = 0; i < cntQuey; i++)     {        if (Q[i][0] == 1)        {            update(tree, 0, 0, N - 1,                   Q[i][1], Q[i][2]);        }        else {            if (Q[i][1] % 2 == 0)             {                System.out.print(FindSum(tree, 0, N - 1,                                Q[i][1], Q[i][2], 0) + " ");            }            else            {                System.out.print(-FindSum(tree, 0, N - 1,                                 Q[i][1], Q[i][2], 0)+ " ");            }        }    }}}Â
// This code is contributed by code_hunt. |
Python3
# Python3Â program to implement# the above approachÂ
# Function to build the segment treedef build(tree, arr, start, end, index):Â
    # If current node is a leaf node    # of the segment tree    if (start == end):        if (start % 2 == 0):Â
            # Update tree[index]            tree[index] = arr[start]        else:Â
            # Update tree[index]            tree[index] = -arr[start]        returnÂ
    # Divide the segment tree    mid = start + (end - start) // 2Â
    # Update on L segment tree    build(tree, arr, start, mid, 2 * index + 1)Â
    # Update on R segment tree    build(tree, arr, mid + 1, end, 2 * index + 2)Â
    # Find the sum from L subtree    # and R subtree    tree[index] = tree[2 * index + 1] + tree[2 * index + 2]Â
# Function to update elements at index pos# by val in the segment treedef update(tree, index, start, end, pos, val):Â
    # If current node is a leaf node    if (start == end):Â
        # If current index is even        if (start % 2 == 0):Â
            # Update tree[index]            tree[index] = val        else:Â
            # Update tree[index]            tree[index] = -val        returnÂ
    # Divide the segment tree elements    # into L and R subtree    mid = start + (end - start) // 2Â
    # If element lies in L subtree    if (mid >= pos):        update(tree, 2 * index + 1, start, mid, pos, val)    else:        update(tree, 2 * index + 2, mid + 1, end, pos, val)Â
    # Update tree[index]    tree[index] = tree[2 * index + 1] + tree[2 * index + 2]Â
# Function to find the sum of array elements# in the range [L, R]def FindSum(tree, start, end, L, R, index):Â
    # If start and end not lies in    # the range [L, R]    if (L > end or R < start):        return 0Â
    #If start and end comleately lies    #in the range [L, R]    if (L <= start and R >= end):        return tree[index]    mid = start + (end - start) // 2Â
    # Stores sum from left subtree    X = FindSum(tree, start, mid, L, R, 2 * index + 1)Â
    # Stores sum from right subtree    Y = FindSum(tree, mid + 1, end, L, R, 2 * index + 2)Â
    return X + YÂ
  # Driver codeif __name__ == '__main__':Â
    arr = [1, 2, 3, 4]    N = len(arr)    tree = [0 for i in range(4 * N + 5)]    build(tree, arr, 0, N - 1, 0)    Q = [ [ 2, 0, 3 ], [ 1, 1, 5 ], [ 2, 1, 2 ] ]    cntQuey = 3    for i in range(cntQuey):        if (Q[i][0] == 1):            update(tree, 0, 0, N - 1, Q[i][1], Q[i][2])        else:            if (Q[i][1] % 2 == 0):                print(FindSum(tree, 0, N - 1, Q[i][1], Q[i][2], 0),end=" ")            else:                print(-FindSum(tree, 0, N - 1, Q[i][1], Q[i][2], 0),end=" ")                 # This code is contributed by mohit kumar 29 |
C#
// C# program to implement// the above approachusing System;class GFG {         // Function to build the segment tree    static void build(int[] tree, int[] arr, int start,               int end, int index)    {              // If current node is a leaf node        // of the segment tree        if (start == end)        {              if (start % 2 == 0)             {                      // Update tree[index]                tree[index] = arr[start];            }                  else            {                      // Update tree[index]                tree[index] = -arr[start];            }            return;        }              // Divide the segment tree        int mid = start + (end - start) / 2;              // Update on L segment tree        build(tree, arr, start, mid,              2 * index + 1);              // Update on R segment tree        build(tree, arr, mid + 1, end,              2 * index + 2);              // Find the sum from L subtree        // and R subtree        tree[index] = tree[2 * index + 1] + tree[2 * index + 2];    }          // Function to update elements at index pos    // by val in the segment tree    static void update(int[] tree, int index, int start,                int end, int pos, int val)    {              // If current node is a leaf node        if (start == end)        {                  // If current index is even            if (start % 2 == 0)             {                      // Update tree[index]                tree[index] = val;            }                  else            {                      // Update tree[index]                tree[index] = -val;            }            return;        }              // Divide the segment tree elements        // into L and R subtree        int mid = start + (end - start) / 2;              // If element lies in L subtree        if (mid >= pos)        {                  update(tree, 2 * index + 1, start,                   mid, pos, val);        }        else        {            update(tree, 2 * index + 2, mid + 1,                   end, pos, val);        }              // Update tree[index]        tree[index]            = tree[2 * index + 1] + tree[2 * index + 2];    }          // Function to find the sum of array elements    // in the range [L, R]    static int FindSum(int[] tree, int start, int end,                int L, int R, int index)    {              // If start and end not lies in        // the range [L, R]        if (L > end || R < start)         {            return 0;        }              // If start and end comleately lies        // in the range [L, R]        if (L <= start && R >= end)         {                  return tree[index];        }        int mid = start + (end - start) / 2;              // Stores sum from left subtree        int X = FindSum(tree, start, mid, L,                        R, 2 * index + 1);              // Stores sum from right subtree        int Y = FindSum(tree, mid + 1, end, L,                        R, 2 * index + 2);              return X + Y;    }Â
  // Driver code  static void Main()  {    int[] arr = { 1, 2, 3, 4 };    int N = arr.Length;    int[] tree = new int[4 * N + 5];    build(tree, arr, 0, N - 1, 0);      int[,] Q = { { 2, 0, 3 }, { 1, 1, 5 }, { 2, 1, 2 } };      int cntQuey = 3;    for (int i = 0; i < cntQuey; i++)     {         if (Q[i, 0] == 1)         {            update(tree, 0, 0, N - 1,                   Q[i, 1], Q[i, 2]);        }          else        {            if (Q[i, 1] % 2 == 0)             {                Console.Write(FindSum(tree, 0, N - 1,                                       Q[i, 1], Q[i, 2], 0) + " ");            }            else            {                Console.Write(-FindSum(tree, 0, N - 1,                                        Q[i, 1], Q[i, 2], 0) + " ");            }        }    }  }}Â
// This code is contributed by divyesh072019. |
Javascript
<script>Â
// Javascript program to implement// the above approachÂ
// Function to build the segment treefunction build(tree, arr, start, end, index){Â
    // If current node is a leaf node    // of the segment tree    if (start == end) {Â
        if (start % 2 == 0) {Â
            // Update tree[index]            tree[index] = arr[start];        }Â
        else {Â
            // Update tree[index]            tree[index] = -arr[start];        }        return;    }Â
    // Divide the segment tree    var mid = start + parseInt((end - start) / 2);Â
    // Update on L segment tree    build(tree, arr, start, mid,          2 * index + 1);Â
    // Update on R segment tree    build(tree, arr, mid + 1, end,          2 * index + 2);Â
    // Find the sum from L subtree    // and R subtree    tree[index] = tree[2 * index + 1] + tree[2 * index + 2];}Â
// Function to update elements at index pos// by val in the segment treefunction update(tree, index, start, end, pos, val){Â
    // If current node is a leaf node    if (start == end) {Â
        // If current index is even        if (start % 2 == 0) {Â
            // Update tree[index]            tree[index] = val;        }Â
        else {Â
            // Update tree[index]            tree[index] = -val;        }        return;    }Â
    // Divide the segment tree elements    // into L and R subtree    var mid = start + parseInt((end - start) / 2);Â
    // If element lies in L subtree    if (mid >= pos) {Â
        update(tree, 2 * index + 1, start,               mid, pos, val);    }    else {        update(tree, 2 * index + 2, mid + 1,               end, pos, val);    }Â
    // Update tree[index]    tree[index]        = tree[2 * index + 1] + tree[2 * index + 2];}Â
// Function to find the sum of array elements// in the range [L, R]function FindSum(tree, start, end, L, R, index){Â
    // If start and end not lies in    // the range [L, R]    if (L > end || R < start) {        return 0;    }Â
    // If start and end comleately lies    // in the range [L, R]    if (L <= start && R >= end) {Â
        return tree[index];    }    var mid = start + parseInt((end - start) / 2);Â
    // Stores sum from left subtree    var X = FindSum(tree, start, mid, L,                    R, 2 * index + 1);Â
    // Stores sum from right subtree    var Y = FindSum(tree, mid + 1, end, L,                    R, 2 * index + 2);Â
    return X + Y;}Â
var arr = [1, 2, 3, 4 ];var N = arr.length;var tree = Array(4*N+5).fill(0);build(tree, arr, 0, N - 1, 0);var Q = [ [ 2, 0, 3 ], [ 1, 1, 5 ], [ 2, 1, 2 ] ];var cntQuey = 3;for (var i = 0; i < cntQuey; i++) {    if (Q[i][0] == 1) {        update(tree, 0, 0, N - 1,               Q[i][1], Q[i][2]);    }    else {        if (Q[i][1] % 2 == 0) {            document.write(FindSum(tree, 0, N - 1,                            Q[i][1], Q[i][2], 0)                 + " ");        }        else {            document.write( -FindSum(tree, 0, N - 1,                             Q[i][1], Q[i][2], 0)                 + " ");        }    }}Â
Â
</script> |
-2 2
Â
Time Complexity: O(|Q| * log(N))Â
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
