1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| from collections.abc import Callable from typing import Generic, TypeVar
T = TypeVar("T")
class SparseTable(Generic[T]): def __init__(self, data: list[T], func: Callable[[T, T], T]) -> None: self.func = func self.st = st = [data] i, N = 1, len(st[0]) while 2 * i <= N: pre = st[-1] st.append([func(pre[j], pre[j + i]) for j in range(N - 2 * i + 1)]) i <<= 1
def query(self, begin: int, end: int) -> T: assert 0 <= begin < end <= len(self.st[0]) lg = (end - begin).bit_length() - 1 return self.func(self.st[lg][begin], self.st[lg][end - (1 << lg)])
|