"""Segment tree (iterative, for range minimum queries).

Idea
----
A binary tree over the array where each node stores the answer (here, the
minimum) for a segment. Leaves are single elements; a parent combines its two
children. Any range splits into O(log n) whole nodes, so range queries and
point updates are both O(log n). This bottom-up version stores the tree in an
array of size 2n: leaves at n..2n-1 and the parent of node i at i // 2.

Swap ``min`` for ``max``, ``+``, ``gcd`` or any associative operation with an
identity value to answer other range queries.

Complexity
----------
build: O(n); update / query: O(log n)
Space: O(n)
"""

from collections.abc import Callable, Sequence
from typing import Any


class SegmentTree:
    def __init__(
        self,
        values: Sequence[Any],
        combine: Callable[[Any, Any], Any] = min,
        identity: Any = float("inf"),
    ) -> None:
        self.n = len(values)
        self.combine = combine
        self.identity = identity
        self.tree = [identity] * self.n + list(values)
        for i in range(self.n - 1, 0, -1):
            self.tree[i] = combine(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, index: int, value: Any) -> None:
        """Set element ``index`` (0-based) to ``value``."""
        i = index + self.n
        self.tree[i] = value
        while i > 1:
            i //= 2
            self.tree[i] = self.combine(self.tree[2 * i], self.tree[2 * i + 1])

    def query(self, left: int, right: int) -> Any:
        """Combine elements left..right inclusive (0-based)."""
        result_left = result_right = self.identity
        lo, hi = left + self.n, right + self.n + 1
        while lo < hi:
            if lo & 1:
                result_left = self.combine(result_left, self.tree[lo])
                lo += 1
            if hi & 1:
                hi -= 1
                result_right = self.combine(self.tree[hi], result_right)
            lo //= 2
            hi //= 2
        return self.combine(result_left, result_right)
