![]() |
VOOZH | about |
Let us consider the following problem to understand Segment Trees.
We have an array arr[0 . . . n-1]. We should be able to
1 Find the xor of elements from index l to r where 0 <= l <= r <= n-1.
2 Change value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1.
Similar to Sum of Given Range.
A simple solution is to run a loop from l to r and calculate xor of elements in given range. To update a value, simply do arr[i] = x. The first operation takes O(n) time and second operation takes O(1) time.
Efficient Approach:
If the number of query and updates are equal, we can perform both the operations in O(log n) time. We can use a Segment Tree to do both operations in O(Logn) time.
Representation of Segment trees
1. Leaf Nodes are the elements of the input array.
2. Each internal node represents some merging of the leaf nodes. The merging may be different for different problems. For this problem, merging is Xor of leaves under a node.
An array representation of tree is used to represent Segment Trees. For each node at index i, the left child is at index 2*i+1, right child at 2*i+2 and the parent is at (i-1)/2.
Query for Product of given range
Once the tree is constructed, how to get the Xor using the constructed segment tree. Following is algorithm to get the xor of elements.
int getXor(node, l, r)
{
if range of node is within l and r
return value in node
else if range of node is completely outside l and r
return 0
else
return getXor(node's left child, l, r) ^
getXor(node's right child, l, r)
}
Output:
Xor of values in given range = 7 Updated Xor of values in given range = 14