使用Python写一个线段树模板
时间: 2024-03-30 17:11:32 浏览: 67
好的,这个问题属于计算机科学方面,我可以为你提供线段树模板的Python代码:
```python
class SegmentTree():
def __init__(self, nums):
self.nums = nums
self.tree = [0] * 4 * len(nums)
self.build(1, 0, 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, start, mid)
self.build(2*node+1, mid+1, end)
self.tree[node] = self.tree[2*node] + self.tree[2*node+1]
def update(self, node, start, end, idx, val):
if start == end:
self.nums[idx] = val
self.tree[node] = val
else:
mid = (start + end) // 2
if idx >= start and idx <= mid:
self.update(2*node, start, mid, idx, val)
else:
self.update(2*node+1, mid+1, end, idx, val)
self.tree[node] = self.tree[2*node] + self.tree[2*node+1]
def query(self, node, start, end, left, right):
if start > right or end < left:
return 0
if start >= left and end <= right:
return self.tree[node]
mid = (start + end) // 2
return self.query(2*node, start, mid, left, right) + self.query(2*node+1, mid+1, end, left, right)
```
这是一个基本的线段树模板,包含了建树、更新和查询操作。您可以根据需要进行修改和扩展。
阅读全文