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 sum of elements from index l to r where 0 <= l <= r <= n-1 2 Change value of a specified element of the array arr[i] = x where 0 <= i <= n-1. A simple solution is to run a loop from l to r and calculate sum 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. Another solution is to create another array and store sum from start to i at the ith index in this array.
Read full article from Segment Tree | Set 1 (Sum of given range) | GeeksforGeeks
No comments:
Post a Comment