ST表
求区间 最大值最小值
O(nlogn) 预处理, O(1) 查询 不可修改
class RMQ:
def __init__(self, init):
self.N = len(init)
self.LOGN = int(math.log2(self.N) + 1)
self.f = [[0] * self.N for _ in range(self.LOGN)]
for i in range(self.N):
self.f[0][i] = init[i]
for i in range(1, self.LOGN):
for j in range(self.N - (1 << i) + 1):
self.f[i][j] = max(self.f[i - 1][j], self.f[i - 1][j + (1 << (i - 1))])
def query(self, l, r):
k = int(math.log2(r - l))
return max(self.f[k][l], self.f[k][r - (1 << k)])
树状数组
需满足结合律和可查分,比如和,乘积,异或和
单点修改,区间查询
import typing
class FenwickTree:
'''Reference: https://en.wikipedia.org/wiki/Fenwick_tree'''
def __init__(self, n: int = 0) -> None:
self._n = n
self.data = [0] * n
def add(self, p: int, x: typing.Any) -> None:
assert 0 <= p < self._n
p += 1
while p <= self._n:
self.data[p - 1] += x
p += p & -p
def sum(self, left: int, right: int) -> typing.Any:
assert 0 <= left <= right <= self._n
return self._sum(right) - self._sum(left)
def _sum(self, r: int) -> typing.Any:
s = 0
while r > 0:
s += self.data[r - 1]
r -= r & -r
return s