📅  最后修改于: 2023-12-03 15:41:14.895000             🧑  作者: Mango
细分树(Segment Tree)是一种常见的数据结构,用于解决区间查询问题。它将一个数组细分为若干个区间,每个区间对应一个节点,从而构成一棵树形结构。细分树基于典型的数据结构二叉堆树(Binary Heap)。它可以支持动态底层数据结构,支持范围查询和数据修改。
以下是一份基于Python的细分树的简单设置:
class SegmentTree:
def __init__(self, data, func=min, filler=float("inf")):
"""初始化"""
self._len = len(data)
self._size = (1 << (self._len - 1)).bit_length()
self.tree = [filler] * (2 * self._size)
self.func = func
self._build(data)
def __getitem__(self, index):
"""获取元素"""
return self.tree[index + self._size]
def _build(self, data):
"""构建"""
current_offset = self._size
for value in data:
self.tree[current_offset] = value
current_offset += 1
for current_offset in range(self._size - 1, -1, -1):
left, right = 2 * current_offset, 2 * current_offset + 1
self.tree[current_offset] = self.func(
self.tree[left], self.tree[right])
def __setitem__(self, index, value):
"""设置元素"""
_index = index + self._size
self.tree[_index] = value
current_offset = _index // 2
while current_offset:
left, right = 2 * current_offset, 2 * current_offset + 1
self.tree[current_offset] = self.func(
self.tree[left], self.tree[right])
current_offset //= 2
def query(self, start, end):
"""查询"""
if start > end:
return None
start += self._size
end += self._size
result = self.tree[start]
while start < end:
if start % 2 == 0:
result = self.func(result, self.tree[start+1])
if end % 2 == 1:
result = self.func(result, self.tree[end-1])
start //= 2
end //= 2
return result
以下是一份基于Python的对细分树进行节点更新和范围最大查询的代码:
def max_range_query(tree, start, end):
"""带有节点更新的范围最大查询"""
if start > end:
return float("-inf")
max_val = float("-inf")
tree[start] = end # 标记该区间已被占用
while start < end:
if start % 2 == 0:
start += 1
else:
max_val = max(max_val, tree[start])
start //= 2
if end % 2 == 1:
end -= 1
else:
max_val = max(max_val, tree[end])
end //= 2
if start == end:
max_val = max(max_val, tree[start])
return max_val
tree = SegmentTree([0]*8)
print(max_range_query(tree, 2, 5)) # 输出3
tree[3] = 8
print(max_range_query(tree, 2, 5)) # 输出8
以上代码实现了细分树的基本功能,也实现了带有节点更新的范围最大查询。希望本文对读者有所帮助。