用python写一段线段树求最小值的代码
时间: 2023-03-29 13:03:49 浏览: 108
以下是 Python 代码实现线段树求最小值:
```python
class SegmentTree:
def __init__(self, nums):
self.nums = nums
self.tree = [] * (4 * len(nums))
self.build(, , len(nums) - 1)
def build(self, node, start, end):
if start == end:
self.tree[node] = self.nums[start]
else:
mid = (start + end) // 2
self.build(2 * node + 1, start, mid)
self.build(2 * node + 2, mid + 1, end)
self.tree[node] = min(self.tree[2 * node + 1], self.tree[2 * node + 2])
def query(self, node, start, end, left, right):
if right < start or end < left:
return float('inf')
if left <= start and end <= right:
return self.tree[node]
mid = (start + end) // 2
return min(self.query(2 * node + 1, start, mid, left, right), self.query(2 * node + 2, mid + 1, end, left, right))
nums = [1, 3, 2, 7, 9, 11]
tree = SegmentTree(nums)
print(tree.query(, , len(nums) - 1, 1, 4)) # 输出 2
```
希望对您有所帮助!
阅读全文