Levelwise Alternating GCD and LCM of nodes in Segment Tree
A Levelwise GCD/LCM alternating segment tree is a segment tree, such that at every level the operations GCD and LCM alternate. In other words at Level 1 the left and right sub-trees combine together by the GCD operation i.e Parent node = Left Child GCD Right Child and on Level 2 the left
and right sub-trees combine together by the LCM operation i.e Parent node = Left Child LCM Right Child
Such a type of Segment tree has the following type of structure:

The operations (GCD) and (LCM) indicate which operation was carried out to merge the child nodes
Given N leaf nodes, the task is to build such a segment tree and print the root node.
Examples:
Input : arr[] = { 5, 4, 8, 10, 6 }
Output : Value at Root Node = 2
Explanation : The image given above shows the
segment tree corresponding to the given
set leaf nodes.
Prerequisites: Segment Trees
In this Segment Tree, we carry two operations:- GCD and LCM.
Now, along with the information which is passed recursively for the sub-trees, information regarding the operation to be carried out at that level is also passed since these operations alternate levelwise. It is 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 GCD and LCM by 0 and 1 respectively. Then, if at Level i GCD operation is performed then at Level (i + 1) LCM operation will be performed. Thus 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}
Careful analysis of the image suggests that if the height of the tree is even then the root node is a result of LCM operation of its left and right children else a result of GCD operation.
#include <bits/stdc++.h> using namespace std; // Recursive function to return gcd of a and b int gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a); } // A utility function to get the middle index from // corner indexes. int getMid(int s, int e) { return s + (e - s) / 2; } void STconstructUtill(int arr[], int ss, int se, int* st, int si, int op) { // 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) STconstructUtill(arr, ss, mid, st, si * 2 + 1, !op); STconstructUtill(arr, mid + 1, se, st, si * 2 + 2, !op); // merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do GCD else LCM if (op == 1) { // GCD operation st[si] = __gcd(st[2 * si + 1], st[2 * si + 2]); } else { // LCM operation st[si] = (st[2 * si + 1] * st[2 * si + 2]) / (gcd(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 STconstructUtil() to fill the allocated memory */int* STconstruct(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(GCD) if Height of tree is // even else it is 0(LCM) for the root node int opAtRoot = (x % 2 == 0 ? 0 : 1); // Fill the allocated memory st STconstructUtill(arr, 0, n - 1, st, 0, opAtRoot); // Return the constructed segment tree return st; } int main() { int arr[] = { 5, 4, 8, 10, 6 }; int n = sizeof(arr) / sizeof(arr[0]); // Build segment tree int* st = STconstruct(arr, n); // 0-based indexing in segment tree int rootIndex = 0; cout << "Value at Root Node = " << st[rootIndex]; return 0; } |
Output:
Value at Root Node = 2
Time complexity for tree construction is O(n), as there are total 2*n-1 nodes and value at every node us calculated at once.
Now to perform point updates i.e. update the value with given index and value, can be done by traversing down the tree to the leaf node and performing 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,
arr[2] = 7
Now the updated segment tree looks like this:

Here nodes in black denote the fact that they are updated.
#include <bits/stdc++.h> using namespace std; // Recursive function to return gcd of a and b int gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a); } // A utility function to get the middle index from // corner indexes. int getMid(int s, int e) { return s + (e - s) / 2; } void STconstructUtill(int arr[], int ss, int se, int* st, int si, int op) { // 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) STconstructUtill(arr, ss, mid, st, si * 2 + 1, !op); STconstructUtill(arr, mid + 1, se, st, si * 2 + 2, !op); // merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do GCD else LCM if (op == 1) { // GCD operation st[si] = gcd(st[2 * si + 1], st[2 * si + 2]); } else { // LCM operation st[si] = (st[2 * si + 1] * st[2 * si + 2]) / (gcd(st[2 * si + 1], st[2 * si + 2])); } } void updateUtil(int* st, int ss, int se, int ind, int val, int si, int op) { // Base Case: If the input index lies outside // this segment if (ind < ss || ind > 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 == ind) { 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) updateUtil(st, ss, mid, ind, val, 2 * si + 1, !op); updateUtil(st, mid + 1, se, ind, val, 2 * si + 2, !op); // merge the left and right subtrees by checking // the operation to be carried. If operation = 1, // then do GCD else LCM if (op == 1) { // GCD operation st[si] = gcd(st[2 * si + 1], st[2 * si + 2]); } else { // LCM operation st[si] = (st[2 * si + 1] * st[2 * si + 2]) / (gcd(st[2 * si + 1], st[2 * si + 2])); } } void update(int arr[], int* st, int n, int ind, int val) { // Check for erroneous input index if (ind < 0 || ind > n - 1) { printf("Invalid Input"); return; } // Height of segment tree int x = (int)(ceil(log2(n))); // operation = 1(GCD) if Height of tree is // even else it is 0(LCM) for the root node int opAtRoot = (x % 2 == 0 ? 0 : 1); arr[ind] = val; // Update the values of nodes in segment tree updateUtil(st, 0, n - 1, ind, val, 0, opAtRoot); } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls STconstructUtil() to fill the allocated memory */int* STconstruct(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(GCD) if Height of tree is // even else it is 0(LCM) for the root node int opAtRoot = (x % 2 == 0 ? 0 : 1); // Fill the allocated memory st STconstructUtill(arr, 0, n - 1, st, 0, opAtRoot); // Return the constructed segment tree return st; } int main() { int arr[] = { 5, 4, 8, 10, 6 }; int n = sizeof(arr) / sizeof(arr[0]); // Build segment tree int* st = STconstruct(arr, n); // 0-based indexing in segment tree int rootIndex = 0; cout << "Old Value at Root Node = " << st[rootIndex] << endl; // perform update arr[2] = 7 update(arr, st, n, 2, 7); cout << "New Value at Root Node = " << st[rootIndex] << endl; return 0; } |
Output:
Old Value at Root Node = 2 New Value at Root Node = 1
The time complexity of update is also O(Logn). To update a leaf value, one node is processed at every level and number of levels is O(Logn).
Recommended Posts:
- Levelwise Alternating OR and XOR operations in Segment Tree
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)
- Cartesian tree from inorder traversal | Segment Tree
- LIS using Segment Tree
- Segment Tree | Set 3 (XOR of given range)
- Segment Tree | Set 1 (Sum of given range)
- Reconstructing Segment Tree
- Segment Tree | (XOR of a given range )
- Lazy Propagation in Segment Tree
- Lazy Propagation in Segment Tree | Set 2
- Two Dimensional Segment Tree | Sub-Matrix Sum
- Segment tree | Efficient implementation
- Persistent Segment Tree | Set 1 (Introduction)
- Smallest subarray with GCD as 1 | Segment Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Akanksha_Rai


