forked from UTSAVS26/PyVerse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsegment_tree.py
More file actions
81 lines (69 loc) · 2.35 KB
/
Copy pathsegment_tree.py
File metadata and controls
81 lines (69 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""
Segment Tree Data Structure
A Segment Tree is a binary tree used for efficient range queries and updates
on arrays. Common operations include range sum, range min/max, and point updates.
Time Complexity:
- Build: O(n)
- Query: O(log n)
- Update: O(log n)
This implementation supports range sum queries and point updates.
"""
class SegmentTree:
def __init__(self, data):
"""
Initialize the Segment Tree with an input array.
Args:
data (List[int]): The input array to build the segment tree from.
"""
if not data:
raise ValueError("Input array must not be empty.")
self.n = len(data)
self.tree = [0] * (2 * self.n)
# Build the tree
for i in range(self.n):
self.tree[self.n + i] = data[i]
for i in range(self.n - 1, 0, -1):
self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
def update(self, index, value):
"""
Update the element at index to value.
Args:
index (int): The index to update.
value (int): The new value.
"""
if not (0 <= index < self.n):
raise IndexError("Index out of bounds.")
pos = index + self.n
self.tree[pos] = value
while pos > 1:
pos //= 2
self.tree[pos] = self.tree[2 * pos] + self.tree[2 * pos + 1]
def query(self, left, right):
"""
Compute the sum of elements in the range [left, right].
Args:
left (int): Left index (inclusive).
right (int): Right index (inclusive).
Returns:
int: The sum in the range [left, right].
"""
if not (0 <= left <= right < self.n):
raise IndexError("Query indices out of bounds.")
left += self.n
right += self.n
result = 0
while left <= right:
if left % 2 == 1:
result += self.tree[left]
left += 1
if right % 2 == 0:
result += self.tree[right]
right -= 1
left //= 2
right //= 2
return result
def __str__(self):
"""String representation of the segment tree (for debugging)."""
return f"SegmentTree({self.tree[self.n:self.n + self.n]})"
def __repr__(self):
return f"SegmentTree(size={self.n})"