class SegmentTree:
def __init__(self, data):
"""
Initializes the segment tree with the given data.
:param data: List of integers (or floats).
"""
self.n = len(data)
# The size of the segment tree array is typically 4*n to be safe
self.tree = [0] * (4 * self.n)
self._build(data, 0, 0, self.n - 1)
def _build(self, data, node, start, end):
"""
Recursively builds the tree.
:param node: Index of the current node in the tree array.
:param start: Start index of the segment in the original data.
:param end: End index of the segment in the original data.
"""
if start == end:
# Leaf node
self.tree[node] = data[start]
else:
mid = (start + end) // 2
left_child = 2 * node + 1
right_child = 2 * node + 2
# Build left and right children
self._build(data, left_child, start, mid)
self._build(data, right_child, mid + 1, end)
# Internal node = sum of children (change this logic for Min/Max/GCD)
self.tree[node] = self.tree[left_child] + self.tree[right_child]
def update(self, index, value):
"""
Updates the value at a specific index in the original data.
"""
self._update(0, 0, self.n - 1, index, value)
def _update(self, node, start, end, index, value):
if start == end:
# Leaf node: update the value
self.tree[node] = value
else:
mid = (start + end) // 2
left_child = 2 * node + 1
right_child = 2 * node + 2
if index <= mid:
# Index is in the left child
self._update(left_child, start, mid, index, value)
else:
# Index is in the right child
self._update(right_child, mid + 1, end, index, value)
# Recalculate the current node value
self.tree[node] = self.tree[left_child] + self.tree[right_child]
def query(self, l, r):
"""
Returns the sum of elements in range [l, r] inclusive.
"""
return self._query(0, 0, self.n - 1, l, r)
def _query(self, node, start, end, l, r):
# Case 1: Range represented by node is completely outside the query range
if r < start or end < l:
return 0 # Identity element for sum (use infinity for Min, -infinity for Max)
# Case 2: Range represented by node is completely inside the query range
if l <= start and end <= r:
return self.tree[node]
# Case 3: Range represented by node is partially inside and partially outside
mid = (start + end) // 2
left_child = 2 * node + 1
right_child = 2 * node + 2
left_sum = self._query(left_child, start, mid, l, r)
right_sum = self._query(right_child, mid + 1, end, l, r)
return left_sum + right_sum
# ==========================================
# Example Usage
# ==========================================
# 1. Create data
data = [1, 3, 5, 7, 9, 11]
# 2. Initialize Segment Tree
st = SegmentTree(data)
print(f"Initial Array: {data}")
print(f"Query (0, 5): {st.query(0, 5)}") # Sum of all: 36
print(f"Query (1, 3): {st.query(1, 3)}") # 3 + 5 + 7 = 15
# 3. Point Update: Change value at index 1 from 3 to 10
print("\nUpdating index 1 to value 10...")
st.update(1, 10)
# 4. Query again
print(f"Query (0, 5): {st.query(0, 5)}") # 1 + 10 + 5 + 7 + 9 + 11 = 43
print(f"Query (1, 3): {st.query(1, 3)}") # 10 + 5 + 7 = 22