class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""
Initializes the Segment Tree.
:param data: The initial list of elements.
:param default: The default value for out-of-bounds or neutral elements (e.g., 0 for sum, inf for min).
:param func: The associative function to perform (e.g., sum, min, max).
"""
self.n = len(data)
self.default = default
self.func = func
# The segment tree array size is typically 4*n to be safe
self.size = 4 * self.n
self.tree = [self.default] * self.size
# Build the tree
self._build(1, 0, self.n - 1, data)
def _build(self, node, start, end, data):
"""Recursively builds the tree."""
if start == end:
self.tree[node] = data[start]
else:
mid = (start + end) // 2
left_child = 2 * node
right_child = 2 * node + 1
self._build(left_child, start, mid, data)
self._build(right_child, mid + 1, end, data)
self.tree[node] = self.func(self.tree[left_child], self.tree[right_child])
def update(self, index, value):
"""Public method to update a value at a specific index."""
self._update(1, 0, self.n - 1, index, value)
def _update(self, node, start, end, index, value):
"""Recursively updates the tree."""
if start == end:
# Leaf node, update directly
self.tree[node] = value
else:
mid = (start + end) // 2
left_child = 2 * node
right_child = 2 * node + 1
if index <= mid:
self._update(left_child, start, mid, index, value)
else:
self._update(right_child, mid + 1, end, index, value)
# Update the current node after child is updated
self.tree[node] = self.func(self.tree[left_child], self.tree[right_child])
def query(self, l, r):
"""Public method to query range [l, r] inclusive."""
return self._query(1, 0, self.n - 1, l, r)
def _query(self, node, start, end, l, r):
"""Recursively queries the tree."""
# Case 1: Range represented by node is completely outside the query range
if r < start or end < l:
return self.default
# 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
right_child = 2 * node + 1
left_res = self._query(left_child, start, mid, l, r)
right_res = self._query(right_child, mid + 1, end, l, r)
return self.func(left_res, right_res)
# ==========================================
# Example Usage
# ==========================================
if __name__ == "__main__":
# 1. Initialize data
data = [1, 3, 5, 7, 9, 11]
# 2. Create Segment Tree for Sum
# default=0 because adding 0 doesn't change sum
st_sum = SegmentTree(data, default=0, func=lambda a, b: a + b)
print(f"Initial Array: {data}")
print(f"Sum of range [1, 3] (3+5+7): {st_sum.query(1, 3)}") # Expected: 15
# 3. Perform Point Update
# Update index 1 (value 3) to value 10
print("\nUpdating index 1 to value 10...")
st_sum.update(1, 10)
# Check new sum
print(f"Sum of range [1, 3] (10+5+7): {st_sum.query(1, 3)}") # Expected: 22
# 4. Create Segment Tree for Minimum
# default=float('inf') because min(x, inf) is x
st_min = SegmentTree(data, default=float('inf'), func=min)
print(f"\nMin of range [0, 4]: {st_min.query(0, 4)}") # Expected: 1