A Levelwise OR/XOR alternating segment tree is a segment tree, such that at every level the operations OR and XOR alternate. In other words at Level 1 the left and right sub-trees combine together by the OR operation i.e Parent node = Left Child OR Right Child and on Level 2 the left
and right sub-trees combine together by the XOR operation i.e Parent node = Left Child XOR Right Child
Such a type of Segment tree has the following type of structure:
The operations (OR) and (XOR) indicate which operation was carried out to merge the child node
Given 2N leaf nodes, the task is to build such a segment tree and print the root node
Examples:
Input : Leaves = {1, 6, 3, 7, 5, 9, 10, 4} Output : Value at Root Node = 3 Explanation : The image given above shows the segment tree corresponding to the given set leaf nodes.
This is an Extension to the Classical Segment Tree where we represent each node as an integer and the parent node is built by first building the left and the right subtrees and then combining the results of the left and the right children into the parent node. This merging of the left and right children into the parent node is done by consistent operations, For example, MIN()/MAX() in Range Minimum Queries, Sum, XOR, OR, AND, etc. By consistent operations, we mean that this operation is performed to merge any node’s left and right child into the parent node by carrying the operation say OP on their results, where OP is a consistent operation.
In this Segment tree, we carry two operations that are -: OR and XOR.
Now we build the Segment tree in a similar fashion as we do in the classical version, but now when we recursively pass the information for the sub-trees we will also pass information regarding the operation to be carried out at that level since these operations alternate levelwise. It’s important to note that a parent node when calls its left and right children the same operation information is passed to both the children as they are on the same level.
let’s represent the two operations i.e OR and XOR by 0 and 1 respectively. Then if at Level i we have an OR operation at Level (i + 1) we will have an XOR operation. There if Level i has 0 as operation then level (i + 1) will have 1 as operation
Operation at Level (i + 1) = ! (Operation at Level i) where, Operation at Level i ? {0, 1}
The parent-child relationship for a segment tree node is shown in the below image:
Now, we need to look at the operation to be carried out at root node.
If we carefully look at the image then it would be easy to figure out that if the height of the tree is even then the root node is a result of XOR operation of its left and right children else a result of OR operation.
C++
// C++ program to build levelwise OR/XOR alternating // Segment tree #include <bits/stdc++.h> using namespace std; // A utility function to get the middle index from // corner indexes. int getMid( int s, int e) { return s + (e - s) / 2; } // A recursive function that constructs Segment Tree // for array[ss..se]. // si is index of current node in segment tree st // operation denotes which operation is carried out // at that level to merge the left and right child. // It's either 0 or 1. void constructSTUtil( int arr[], int ss, int se, int * st, int si, int operation) { // If there is one element in array, store it // in current node of segment tree and return if (ss == se) { st[si] = arr[ss]; return ; } // If there are more than one elements, then // recur for left and right subtrees and store // the sum of values in this node int mid = getMid(ss, se); // Build the left and the right subtrees by // using the fact that operation at level // (i + 1) = ! (operation at level i) constructSTUtil(arr, ss, mid, st, si * 2 + 1, !operation); constructSTUtil(arr, mid + 1, se, st, si * 2 + 2, !operation); // merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do OR else XOR if (operation == 1) { // OR operation st[si] = (st[2 * si + 1] | st[2 * si + 2]); } else { // XOR operation st[si] = (st[2 * si + 1] ^ st[2 * si + 2]); } } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int * constructST( int arr[], int n) { // Allocate memory for segment tree // Height of segment tree int x = ( int )( ceil (log2(n))); // Maximum size of segment tree int max_size = 2 * ( int ) pow (2, x) - 1; // Allocate memory int * st = new int [max_size]; // operation = 1(XOR) if Height of tree is // even else it is 0(OR) for the root node int operationAtRoot = (x % 2 == 0 ? 0 : 1); // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0, operationAtRoot); // Return the constructed segment tree return st; } // Driver Code int main() { // leaf nodes int leaves[] = { 1, 6, 3, 7, 5, 9, 10, 4 }; int n = sizeof (leaves) / sizeof (leaves[0]); // Build the segment tree int * segmentTree = constructST(leaves, n); // Root node is at index 0 considering // 0-based indexing in segment Tree int rootIndex = 0; // print value at rootIndex cout << "Value at Root Node = " << segmentTree[rootIndex]; } |
Java
// Java program to build levelwise OR/XOR alternating // Segment tree class GFG{ // A utility function to get the middle index from // corner indexes. static int getMid( int s, int e) { return s + (e - s) / 2 ; } // A recursive function that constructs Segment Tree // for array[ss..se]. // si is index of current node in segment tree st // operation denotes which operation is carried out // at that level to merge the left and right child. // It's either 0 or 1. static void constructSTUtil( int arr[], int ss, int se, int st[], int si, boolean operation) { // If there is one element in array, store it // in current node of segment tree and return if (ss == se) { st[si] = arr[ss]; return ; } // If there are more than one elements, then // recur for left and right subtrees and store // the sum of values in this node int mid = getMid(ss, se); // Build the left and the right subtrees by // using the fact that operation at level // (i + 1) = ! (operation at level i) constructSTUtil(arr, ss, mid, st, si * 2 + 1 , !operation); constructSTUtil(arr, mid + 1 , se, st, si * 2 + 2 , !operation); // Merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do OR else XOR if (operation) { // OR operation st[si] = (st[ 2 * si + 1 ] | st[ 2 * si + 2 ]); } else { // XOR operation st[si] = (st[ 2 * si + 1 ] ^ st[ 2 * si + 2 ]); } } // Function to construct segment tree from // given array. This function allocates // memory for segment tree and calls // constructSTUtil() to fill the allocated memory static int [] constructST( int arr[], int n) { // Allocate memory for segment tree // Height of segment tree int x = ( int )(Math.ceil(Math.log(n) / Math.log( 2 ))); // Maximum size of segment tree int max_size = 2 * ( int )Math.pow( 2 , x) - 1 ; // Allocate memory int [] st = new int [max_size]; // Operation = 1(XOR) if Height of tree is // even else it is 0(OR) for the root node boolean operationAtRoot = !(x % 2 == 0 ); // Fill the allocated memory st constructSTUtil(arr, 0 , n - 1 , st, 0 , operationAtRoot); // Return the constructed segment tree return st; } // Driver Code public static void main(String[] args) { // Leaf nodes int leaves[] = { 1 , 6 , 3 , 7 , 5 , 9 , 10 , 4 }; int n = leaves.length; // Build the segment tree int [] segmentTree = constructST(leaves, n); // Root node is at index 0 considering // 0-based indexing in segment Tree int rootIndex = 0 ; // Print value at rootIndex System.out.println( "Value at Root Node = " + segmentTree[rootIndex]); } } // This code is contributed by sanjeev2552 |
Python3
# Python3 program to build levelwise # OR/XOR alternating Segment tree import math # A utility function to get the # middle index from corner indexes. def getMid(s, e): return s + (e - s) / / 2 # A recursive function that constructs # Segment Tree for array[ss..se]. # 'si' is index of current node in segment # tree 'st', operation denotes which operation # is carried out at that level to merge the # left and right child. It's either 0 or 1. def constructSTUtil(arr, ss, se, st, si, operation): # If there is one element in array, # store it in current node of segment # tree and return if (ss = = se) : st[si] = arr[ss] return # If there are more than one elements, # then recur for left and right subtrees # and store the sum of values in this node mid = getMid(ss, se) # Build the left and the right subtrees by # using the fact that operation at level # (i + 1) = ! (operation at level i) constructSTUtil(arr, ss, mid, st, si * 2 + 1 , not operation) constructSTUtil(arr, mid + 1 , se, st, si * 2 + 2 , not operation) # merge the left and right subtrees # by checking the operation to be # carried. If operation = 1, then # do OR else XOR if (operation = = 1 ) : # OR operation st[si] = (st[ 2 * si + 1 ] | st[ 2 * si + 2 ]) else : # XOR operation st[si] = (st[ 2 * si + 1 ] ^ st[ 2 * si + 2 ]) ''' Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory ''' def constructST(arr, n): # Allocate memory for segment tree # Height of segment tree x = int (math.ceil(math.log2(n))) # Maximum size of segment tree max_size = 2 * int ( pow ( 2 , x)) - 1 # Allocate memory st = [ 0 ] * max_size # operation = 1(XOR) if Height of tree is # even else it is 0(OR) for the root node operationAtRoot = ( 0 if x % 2 = = 0 else 1 ) # Fill the allocated memory st constructSTUtil(arr, 0 , n - 1 , st, 0 , operationAtRoot) # Return the constructed segment tree return st # Driver Code if __name__ = = "__main__" : # leaf nodes leaves = [ 1 , 6 , 3 , 7 , 5 , 9 , 10 , 4 ] n = len (leaves) # Build the segment tree segmentTree = constructST(leaves, n) # Root node is at index 0 considering # 0-based indexing in segment Tree rootIndex = 0 # print value at rootIndex print ( "Value at Root Node = " , segmentTree[rootIndex]) # This code is contributed by ChitraNayal |
C#
// C# program to build levelwise OR/XOR // alternating Segment tree using System; class GFG{ // A utility function to get the middle // index from corner indexes. static int getMid( int s, int e) { return s + (e - s) / 2; } // A recursive function that constructs Segment Tree // for array[ss..se]. // si is index of current node in segment tree st // operation denotes which operation is carried out // at that level to merge the left and right child. // It's either 0 or 1. static void constructSTUtil( int [] arr, int ss, int se, int [] st, int si, bool operation) { // If there is one element in array, store it // in current node of segment tree and return if (ss == se) { st[si] = arr[ss]; return ; } // If there are more than one elements, then // recur for left and right subtrees and store // the sum of values in this node int mid = getMid(ss, se); // Build the left and the right subtrees by // using the fact that operation at level // (i + 1) = ! (operation at level i) constructSTUtil(arr, ss, mid, st, si * 2 + 1, !operation); constructSTUtil(arr, mid + 1, se, st, si * 2 + 2, !operation); // Merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do OR else XOR if (operation) { // OR operation st[si] = (st[2 * si + 1] | st[2 * si + 2]); } else { // XOR operation st[si] = (st[2 * si + 1] ^ st[2 * si + 2]); } } // Function to construct segment tree from // given array. This function allocates // memory for segment tree and calls // constructSTUtil() to fill the allocated memory static int [] constructST( int [] arr, int n) { // Allocate memory for segment tree // Height of segment tree int x = ( int )(Math.Ceiling(Math.Log(n) / Math.Log(2))); // Maximum size of segment tree int max_size = 2 * ( int )Math.Pow(2, x) - 1; // Allocate memory int [] st = new int [max_size]; // Operation = 1(XOR) if Height of tree is // even else it is 0(OR) for the root node bool operationAtRoot = !(x % 2 == 0); // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0, operationAtRoot); // Return the constructed segment tree return st; } // Driver Code static public void Main() { // Leaf nodes int [] leaves = { 1, 6, 3, 7, 5, 9, 10, 4 }; int n = leaves.Length; // Build the segment tree int [] segmentTree = constructST(leaves, n); // Root node is at index 0 considering // 0-based indexing in segment Tree int rootIndex = 0; // Print value at rootIndex Console.WriteLine( "Value at Root Node = " + segmentTree[rootIndex]); } } // This code is contributed by rag2127 |
Javascript
<script> // Javascript program to build levelwise OR/XOR // alternating Segment tree // A utility function to get the middle // index from corner indexes. function getMid(s, e) { return s + Math.floor((e - s) / 2); } // A recursive function that constructs Segment Tree // for array[ss..se]. // si is index of current node in segment tree st // operation denotes which operation is carried out // at that level to merge the left and right child. // It's either 0 or 1. function constructSTUtil(arr, ss, se, st, si, operation) { // If there is one element in array, store it // in current node of segment tree and return if (ss == se) { st[si] = arr[ss]; return ; } // If there are more than one elements, then // recur for left and right subtrees and store // the sum of values in this node let mid = getMid(ss, se); // Build the left and the right subtrees by // using the fact that operation at level // (i + 1) = ! (operation at level i) constructSTUtil(arr, ss, mid, st, si * 2 + 1, !operation); constructSTUtil(arr, mid + 1, se, st, si * 2 + 2, !operation); // Merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do OR else XOR if (operation) { // OR operation st[si] = (st[2 * si + 1] | st[2 * si + 2]); } else { // XOR operation st[si] = (st[2 * si + 1] ^ st[2 * si + 2]); } } // Function to construct segment tree from // given array. This function allocates // memory for segment tree and calls // constructSTUtil() to fill the allocated memory function constructST(arr, n) { // Allocate memory for segment tree // Height of segment tree let x = Math.ceil(Math.log(n) / Math.log(2)); // Maximum size of segment tree let max_size = 2 * Math.pow(2, x) - 1; // Allocate memory let st = new Array(max_size); // Operation = 1(XOR) if Height of tree is // even else it is 0(OR) for the root node let operationAtRoot = !(x % 2 == 0); // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0, operationAtRoot); // Return the constructed segment tree return st; } // Driver Code // Leaf nodes let leaves = [1, 6, 3, 7, 5, 9, 10, 4]; let n = leaves.length; // Build the segment tree let segmentTree = constructST(leaves, n); // Root node is at index 0 considering // 0-based indexing in segment Tree let rootIndex = 0; // Print value at rootIndex document.write( "Value at Root Node = " + segmentTree[rootIndex]); // This code is contributed by gfgking </script> |
Value at Root Node = 3
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.
We can also perform Point Updates in a similar manner. If we get an update to update the leaf at index i of the array leaves then we traverse down the tree to the leaf node and perform the update. While coming back to the root node we build the tree again similar to the build() function by passing the operation to be performed at every level and storing the result of applying that operation on values of its left and right children and storing the result into that node.
Consider the following Segment tree after performing the update,
Leaves[0] = 13
Now the updated segment tree looks like this:
Here the nodes in black denote the fact that they were updated
C++
// C++ program to build levelwise OR/XOR alternating // Segment tree (with updates) #include <bits/stdc++.h> using namespace std; // A utility function to get the middle index from // corner indexes. int getMid( int s, int e) { return s + (e - s) / 2; } // A recursive function that constructs Segment Tree // for array[ss..se]. // si is index of current node in segment tree st // operation denotes which operation is carried out // at that level to merge the left and right child. // Its either 0 or 1. void constructSTUtil( int arr[], int ss, int se, int * st, int si, int operation) { // If there is one element in array, store it in // current node of segment tree and return if (ss == se) { st[si] = arr[ss]; return ; } // If there are more than one elements, then recur // for left and right subtrees and store the sum of // values in this node int mid = getMid(ss, se); // Build the left and the right subtrees by using // the fact that operation at level (i + 1) = ! // (operation at level i) constructSTUtil(arr, ss, mid, st, si * 2 + 1, !operation); constructSTUtil(arr, mid + 1, se, st, si * 2 + 2, !operation); // merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do OR else XOR if (operation == 1) { // OR operation st[si] = (st[2 * si + 1] | st[2 * si + 2]); } else { // XOR operation st[si] = (st[2 * si + 1] ^ st[2 * si + 2]); } } /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. val --> Value to be assigned to arr[i] */ void updateValueUtil( int * st, int ss, int se, int i, int val, int si, int operation) { // Base Case: If the input index lies outside // this segment if (i < ss || i > se) return ; // If the input index is in range of this node, // then update the value of the node and its // children // leaf node if (ss == se && ss == i) { st[si] = val; return ; } int mid = getMid(ss, se); // Update the left and the right subtrees by // using the fact that operation at level // (i + 1) = ! (operation at level i) updateValueUtil(st, ss, mid, i, val, 2 * si + 1, !operation); updateValueUtil(st, mid + 1, se, i, val, 2 * si + 2, !operation); // merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do OR else XOR if (operation == 1) { // OR operation st[si] = (st[2 * si + 1] | st[2 * si + 2]); } else { // XOR operation st[si] = (st[2 * si + 1] ^ st[2 * si + 2]); } } // The function to update a value in input array and // segment tree. It uses updateValueUtil() to update the // value in segment tree void updateValue( int arr[], int * st, int n, int i, int new_val) { // Check for erroneous input index if (i < 0 || i > n - 1) { printf ( "Invalid Input" ); return ; } // Height of segment tree int x = ( int )( ceil (log2(n))); // operation = 1(XOR) if Height of tree is // even else it is 0(OR) for the root node int operationAtRoot = (x % 2 == 0 ? 0 : 1); arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(st, 0, n - 1, i, new_val, 0, operationAtRoot); } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int * constructST( int arr[], int n) { // Allocate memory for segment tree // Height of segment tree int x = ( int )( ceil (log2(n))); // Maximum size of segment tree int max_size = 2 * ( int ) pow (2, x) - 1; // Allocate memory int * st = new int [max_size]; // operation = 1(XOR) if Height of tree is // even else it is 0(OR) for the root node int operationAtRoot = (x % 2 == 0 ? 0 : 1); // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0, operationAtRoot); // Return the constructed segment tree return st; } // Driver Code int main() { int leaves[] = { 1, 6, 3, 7, 5, 9, 10, 4 }; int n = sizeof (leaves) / sizeof (leaves[0]); // Build the segment tree int * segmentTree = constructST(leaves, n); // Root node is at index 0 considering // 0-based indexing in segment Tree int rootIndex = 0; // print old value at rootIndex cout << "Old Value at Root Node = " << segmentTree[rootIndex] << endl; // perform update leaves[0] = 13 updateValue(leaves, segmentTree, n, 0, 13); cout << "New Value at Root Node = " << segmentTree[rootIndex]; return 0; } |
Java
// Java program to build levelwise OR/XOR alternating // Segment tree (with updates) import java.io.*; class GFG { public static int log2( int N) { // calculate log2 N indirectly // using log() method int result = ( int )(Math.log(N) / Math.log( 2 )); return result; } // A utility function to get the middle index from // corner indexes. public static int getMid( int s, int e) { return s + (e - s) / 2 ; } // A recursive function that constructs Segment Tree // for array[ss..se]. // si is index of current node in segment tree st // operation denotes which operation is carried out // at that level to merge the left and right child. // Its either 0 or 1. public static void constructSTUtil( int arr[], int ss, int se, int st[], int si, int operation) { // If there is one element in array, store it in // current node of segment tree and return if (ss == se) { st[si] = arr[ss]; return ; } // If there are more than one elements, then recur // for left and right subtrees and store the sum of // values in this node int mid = getMid(ss, se); // Build the left and the right subtrees by using // the fact that operation at level (i + 1) = ! // (operation at level i) constructSTUtil(arr, ss, mid, st, si * 2 + 1 , operation ^ 1 ); constructSTUtil(arr, mid + 1 , se, st, si * 2 + 2 , operation ^ 1 ); // merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do OR else XOR if (operation == 1 ) { // OR operation st[si] = (st[ 2 * si + 1 ] | st[ 2 * si + 2 ]); } else { // XOR operation st[si] = (st[ 2 * si + 1 ] ^ st[ 2 * si + 2 ]); } } /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. val --> Value to be assigned to arr[i] */ public static void updateValueUtil( int st[], int ss, int se, int i, int val, int si, int operation) { // Base Case: If the input index lies outside // this segment if (i < ss || i > se) return ; // If the input index is in range of this node, // then update the value of the node and its // children // leaf node if (ss == se && ss == i) { st[si] = val; return ; } int mid = getMid(ss, se); // Update the left and the right subtrees by // using the fact that operation at level // (i + 1) = ! (operation at level i) updateValueUtil(st, ss, mid, i, val, 2 * si + 1 , operation ^ 1 ); updateValueUtil(st, mid + 1 , se, i, val, 2 * si + 2 , operation ^ 1 ); // merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do OR else XOR if (operation == 1 ) { // OR operation st[si] = (st[ 2 * si + 1 ] | st[ 2 * si + 2 ]); } else { // XOR operation st[si] = (st[ 2 * si + 1 ] ^ st[ 2 * si + 2 ]); } } // The function to update a value in input array and // segment tree. It uses updateValueUtil() to update the // value in segment tree public static void updateValue( int arr[], int st[], int n, int i, int new_val) { // Check for erroneous input index if (i < 0 || i > n - 1 ) { System.out.print( "Invalid Input" ); return ; } // Height of segment tree int x = ( int )(Math.ceil(log2(n))); // operation = 1(XOR) if Height of tree is // even else it is 0(OR) for the root node int operationAtRoot = (x % 2 == 0 ? 0 : 1 ); arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(st, 0 , n - 1 , i, new_val, 0 , operationAtRoot); } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ public static int [] constructST( int arr[], int n) { // Allocate memory for segment tree // Height of segment tree int x = ( int )(Math.ceil(log2(n))); // Maximum size of segment tree int max_size = 2 * ( int )Math.pow( 2 , x) - 1 ; // Allocate memory int st[] = new int [max_size]; // operation = 1(XOR) if Height of tree is // even else it is 0(OR) for the root node int operationAtRoot = (x % 2 == 0 ? 0 : 1 ); // Fill the allocated memory st constructSTUtil(arr, 0 , n - 1 , st, 0 , operationAtRoot); // Return the constructed segment tree return st; } // Driver code public static void main(String[] args) { int leaves[] = { 1 , 6 , 3 , 7 , 5 , 9 , 10 , 4 }; int n = leaves.length; // Build the segment tree int segmentTree[] = constructST(leaves, n); // Root node is at index 0 considering // 0-based indexing in segment Tree int rootIndex = 0 ; // print old value at rootIndex System.out.println( "Old Value at Root Node = " + segmentTree[rootIndex]); // perform update leaves[0] = 13 updateValue(leaves, segmentTree, n, 0 , 13 ); System.out.print( "New Value at Root Node = " + segmentTree[rootIndex]); } } // This code is contributed by Rohit Pradhan |
Python3
# Python program to build levelwise OR/XOR alternating # Segment tree (with updates) import math def getMid(s, e): return s + (e - s) / / 2 def constructSTUtil(arr, ss, se, st, si, level): # If there is one element in array, store it in # current node of segment tree and return if ss = = se: st[si] = arr[ss] return # If there are more than one elements, then recur # for left and right subtrees and store the sum of # values in this node mid = getMid(ss, se) # Determine the operation to use for merging the left # and right subtrees based on the current level if (level % 2 ) = = 0 : operation = 0 # OR operation else : operation = 1 # XOR operation constructSTUtil(arr, ss, mid, st, si * 2 + 1 , level + 1 ) constructSTUtil(arr, mid + 1 , se, st, si * 2 + 2 , level + 1 ) # merge the left and right subtrees by checking # the operation to be carried. If operation = 1, # then do XOR else OR if operation = = 1 : # XOR operation st[si] = st[ 2 * si + 1 ] ^ st[ 2 * si + 2 ] else : # OR operation st[si] = st[ 2 * si + 1 ] | st[ 2 * si + 2 ] def updateValueUtil(st, ss, se, i, val, si, operation): # Base Case: If the input index lies outside # this segment if i < ss or i > se: return # If the input index is in range of this node, # then update the value of the node and its # children # leaf node if ss = = se and ss = = i: st[si] = val return mid = getMid(ss, se) # Update the left and the right subtrees by # using the fact that operation at level # (i + 1) = ! (operation at level i) updateValueUtil(st, ss, mid, i, val, 2 * si + 1 , not operation) updateValueUtil(st, mid + 1 , se, i, val, 2 * si + 2 , not operation) # merge the left and right subtrees by checking # the operation to be carried. If operation = 1, # then do OR else XOR if operation = = 1 : # OR operation st[si] = st[ 2 * si + 1 ] | st[ 2 * si + 2 ] else : # XOR operation st[si] = st[ 2 * si + 1 ] ^ st[ 2 * si + 2 ] def updateValue(arr, st, n, i, new_val): # Check for erroneous input index if i < 0 or i > n - 1 : print ( "Invalid Input" ) return # Get the height of the tree after update x = int (math.ceil(math.log2(n))) # Determine the operation to use for merging the left # and right subtrees based on the height of the tree if (x % 2 ) = = 0 : operation = 0 # OR operation else : operation = 1 # XOR operation arr[i] = new_val # Update the values of nodes in segment tree updateValueUtil(st, 0 , n - 1 , i, new_val, 0 , operation) # Update the root node operation if operation = = 1 : # XOR operation st[ 0 ] = st[ 1 ] ^ st[ 2 ] else : # OR operation st[ 0 ] = st[ 1 ] | st[ 2 ] def constructST(arr, n): # Height of segment tree x = int (math.ceil(math.log2(n))) # Maximum size of segment tree max_size = 2 * ( 2 * * x) - 1 # Allocate memory for segment tree st = [ 0 ] * max_size # operation = 1(XOR) if Height of tree is # even else it is 0(OR) for the root node operationAtRoot = 1 if x % 2 = = 0 else 0 # Fill the allocated memory st constructSTUtil(arr, 0 , n - 1 , st, 0 , operationAtRoot) # Return the constructed segment tree return st # Driver Code if __name__ = = "__main__" : leaves = [ 1 , 6 , 3 , 7 , 5 , 9 , 10 , 4 ] n = len (leaves) # Build the segment tree segmentTree = constructST(leaves, n) # Root node is at index 0 considering # 0-based indexing in segment Tree rootIndex = 0 # print old value at rootIndex print ( "Old Value at Root Node = " , segmentTree[rootIndex]) # perform update leaves[0] = 13 updateValue(leaves, segmentTree, n, 0 , 13 ) print ( "New Value at Root Node = " , segmentTree[rootIndex]) |
C#
// C# program to build levelwise OR/XOR alternating // Segment tree (with updates) using System; class SegmentTree { // A utility function to get the middle index from // corner indexes. static int GetMid( int s, int e) { return s + (e - s) / 2; } // A recursive function that constructs Segment Tree // for array[ss..se]. // si is index of current node in segment tree st // operation denotes which operation is carried out // at that level to merge the left and right child. // Its either 0 or 1. static void ConstructSTUtil( int [] arr, int ss, int se, int [] st, int si, int operation) { // If there is one element in array, store it in // current node of segment tree and return if (ss == se) { st[si] = arr[ss]; return ; } // If there are more than one elements, then recur // for left and right subtrees and store the sum of // values in this node int mid = GetMid(ss, se); // Build the left and the right subtrees by using // the fact that operation at level (i + 1) = ! // (operation at level i) ConstructSTUtil(arr, ss, mid, st, si * 2 + 1, (operation == 1) ? 0 : 1); ConstructSTUtil(arr, mid + 1, se, st, si * 2 + 2, (operation == 1) ? 0 : 1); // merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do OR else XOR if (operation == 1) // Or Operation st[si] = (st[2 * si + 1] | st[2 * si + 2]); else // XOR operation st[si] = (st[2 * si + 1] ^ st[2 * si + 2]); } /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. val --> Value to be assigned to arr[i] */ static void UpdateValueUtil( int [] st, int ss, int se, int i, int val, int si, int operation) { // Base Case: If the input index lies outside // this segment if (i < ss || i > se) return ; // If the input index is in range of this node, // then update the value of the node and its // children // leaf node if (ss == se && ss == i) { st[si] = val; return ; } int mid = GetMid(ss, se); // Update the left and the right subtrees by // using the fact that operation at level // (i + 1) = ! (operation at level i) UpdateValueUtil(st, ss, mid, i, val, 2 * si + 1, (operation == 1) ? 0 : 1); UpdateValueUtil(st, mid + 1, se, i, val, 2 * si + 2, (operation == 1) ? 0 : 1); // merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do OR else XOR if (operation == 1) // or st[si] = (st[2 * si + 1] | st[2 * si + 2]); else // xor st[si] = (st[2 * si + 1] ^ st[2 * si + 2]); } // The function to update a value in input array and // segment tree. It uses updateValueUtil() to update the // value in segment tree static void UpdateValue( int [] arr, int [] st, int n, int i, int new_val) { // check for erroenous input index if (i < 0 || i > n - 1) { Console.WriteLine( "Invalid Input" ); return ; } // Height of segment tree int x = ( int )(Math.Ceiling(Math.Log(n) / Math.Log(2))); // operation = 1(XOR) if Height of tree is // even else it is 0(OR) for the root node int operationAtRoot = (x % 2 == 0 ? 0 : 1); arr[i] = new_val; // Update the values of nodes in segment tree UpdateValueUtil(st, 0, n - 1, i, new_val, 0, operationAtRoot); } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ static int [] ConstructST( int [] arr, int n) { // Allocate memory for segment tree // Height of segment tree int x = ( int )(Math.Ceiling(Math.Log(n) / Math.Log(2))); int max_size = 2 * ( int )Math.Pow(2, x) - 1; int [] st = new int [max_size]; // operation = 1(XOR) if Height of tree is // even else it is 0(OR) for the root node int operationAtRoot = (x % 2 == 0 ? 0 : 1); ConstructSTUtil(arr, 0, n - 1, st, 0, operationAtRoot); return st; } static void Main() { int [] leaves = { 1, 6, 3, 7, 5, 9, 10, 4 }; int n = leaves.Length; // Build the segment tree int [] segmentTree = ConstructST(leaves, n); // Root node is at index 0 considering // 0-based indexing in segment Tree int rootIndex = 0; Console.Write( "Old Value at Root Node = " ); Console.Write(segmentTree[rootIndex]); // perform update leaves[0] = 13 UpdateValue(leaves, segmentTree, n, 0, 13); Console.Write( "New Value at Root Node = " ); Console.Write(segmentTree[rootIndex]); } } |
Javascript
// Javascript program to build levelwise OR/XOR alternating // Segment tree (with updates) function getMid(s, e) { return s + Math.floor((e - s) / 2); } function constructSTUtil(arr, ss, se, st, si, operation) { if (ss == se) { st[si] = arr[ss]; return ; } let mid = getMid(ss, se); constructSTUtil(arr, ss, mid, st, si * 2 + 1, operation == 1 ? 0 : 1); constructSTUtil(arr, mid + 1, se, st, si * 2 + 2, operation == 1 ? 0 : 1); if (operation == 1) { st[si] = (st[2 * si + 1] | st[2 * si + 2]); } else { st[si] = (st[2 * si + 1] ^ st[2 * si + 2]); } } function updateValueUtil(st, ss, se, i, val, si, operation) { if (i < ss || i > se) { return ; } if (ss == se && ss == i) { st[si] = val; return ; } let mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, val, 2 * si + 1, operation == 1 ? 0 : 1); updateValueUtil(st, mid + 1, se, i, val, 2 * si + 2, operation == 1 ? 0 : 1); if (operation == 1) { st[si] = (st[2 * si + 1] | st[2 * si + 2]); } else { st[si] = (st[2 * si + 1] ^ st[2 * si + 2]); } } function updateValue(arr, st, n, i, new_val) { if (i < 0 || i > n - 1) { console.log( "Invalid Input" ); return ; } let x = Math.ceil(Math.log2(n)); let operationAtRoot = x % 2 == 0 ? 0 : 1; arr[i] = new_val; updateValueUtil(st, 0, n - 1, i, new_val, 0, operationAtRoot); } function constructST(arr, n) { let x = Math.ceil(Math.log2(n)); let st_size = 2 * Math.pow(2, x) - 1; let st = new Array(st_size).fill(0); let operationAtRoot = x % 2 == 0 ? 0 : 1; constructSTUtil(arr, 0, n - 1, st, 0, operationAtRoot); return st; } const leaves = [1, 6, 3, 7, 5, 9, 10, 4]; const n = leaves.length; // Build the segment tree const segmentTree = constructST(leaves, n); // Root node is at index 0 considering // 0-based indexing in segment Tree const rootIndex = 0; console.log(`Old Value at Root Node = ${segmentTree[rootIndex]}`); // perform update leaves[0] = 13 updateValue(leaves, segmentTree, n, 0, 13); console.log(`New Value at Root Node = ${segmentTree[rootIndex]}`); // The code is contributed by Nidhi goel. |
Old Value at Root Node = 3 New Value at Root Node = 11
The time complexity of update is also O(Logn). To update a leaf value, we process one node at every level and number of levels is O(Logn).
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!