"""Guttman R-tree (quadratic split, M = 16, m = 6) in pure Python.

Layout
------
Every entry is a 5-sequence (x0, y0, x1, y1, payload):

* a leaf entry is an immutable tuple (x0, y0, x1, y1, id);
* an internal entry *is* the child node: a mutable list
  [x0, y0, x1, y1, kids], where the first four items are the exact bounding
  rectangle of the node and `kids` is the list of its entries.

So a node and the parent's entry for it are the same object, and the
bounding rectangle stored in a parent is updated in place.  The root is a
node of the same form.  Whether a node's kids are leaf entries is known
from its level (all leaves are at the same depth); the tree records its
height.
"""

from heapq import heappush, heappop

_NEG = -(1 << 62)
_INF = 1 << 90
_IDMASK = 0x7FFFFFFF


def _split(E):
    """Quadratic split of the 17 entries E. Returns (g1, bb1, g2, bb2)."""
    R = [(a, b, c, d, (c - a) * (d - b)) for a, b, c, d, _ in E]
    n = len(R)

    # PickSeeds: the pair wasting the most area.
    bestd = _NEG
    s1 = 0
    s2 = 1
    for i in range(n - 1):
        a0, b0, c0, d0, r0 = R[i]
        ds = [((c if c > c0 else c0) - (a if a < a0 else a0))
              * ((d if d > d0 else d0) - (b if b < b0 else b0)) - r
              for a, b, c, d, r in R[i + 1:]]
        mx = max(ds)
        if mx - r0 > bestd:
            bestd = mx - r0
            s1 = i
            s2 = i + 1 + ds.index(mx)

    g1 = [E[s1]]
    g2 = [E[s2]]
    p0, p1, p2, p3, pa = R[s1]
    q0, q1, q2, q3, qa = R[s2]
    rest = E[:s1] + E[s1 + 1:s2] + E[s2 + 1:]
    restR = R[:s1] + R[s1 + 1:s2] + R[s2 + 1:]

    while rest:
        nr = len(rest)
        if len(g1) + nr <= 6:
            g1 += rest
            for a, b, c, d, _ in restR:
                if a < p0:
                    p0 = a
                if b < p1:
                    p1 = b
                if c > p2:
                    p2 = c
                if d > p3:
                    p3 = d
            break
        if len(g2) + nr <= 6:
            g2 += rest
            for a, b, c, d, _ in restR:
                if a < q0:
                    q0 = a
                if b < q1:
                    q1 = b
                if c > q2:
                    q2 = c
                if d > q3:
                    q3 = d
            break
        # PickNext: the entry with the strongest preference for one group.
        pq = pa - qa
        diffs = [abs(((c if c > p2 else p2) - (a if a < p0 else p0))
                     * ((d if d > p3 else p3) - (b if b < p1 else p1))
                     - ((c if c > q2 else q2) - (a if a < q0 else q0))
                     * ((d if d > q3 else q3) - (b if b < q1 else q1))
                     - pq)
                 for a, b, c, d, _ in restR]
        j = diffs.index(max(diffs))
        a, b, c, d, _ = restR.pop(j)
        e = rest.pop(j)
        n0 = a if a < p0 else p0
        n1 = b if b < p1 else p1
        n2 = c if c > p2 else p2
        n3 = d if d > p3 else p3
        u1 = (n2 - n0) * (n3 - n1)
        m0 = a if a < q0 else q0
        m1 = b if b < q1 else q1
        m2 = c if c > q2 else q2
        m3 = d if d > q3 else q3
        u2 = (m2 - m0) * (m3 - m1)
        d1 = u1 - pa
        d2 = u2 - qa
        if d1 < d2:
            to1 = True
        elif d2 < d1:
            to1 = False
        elif pa < qa:
            to1 = True
        elif qa < pa:
            to1 = False
        else:
            to1 = len(g1) <= len(g2)
        if to1:
            g1.append(e)
            p0 = n0
            p1 = n1
            p2 = n2
            p3 = n3
            pa = u1
        else:
            g2.append(e)
            q0 = m0
            q1 = m1
            q2 = m2
            q3 = m3
            qa = u2
    return g1, (p0, p1, p2, p3), g2, (q0, q1, q2, q3)


class RTree:
    __slots__ = ("root", "h", "n")

    def __init__(self) -> None:
        self.root = [0, 0, 0, 0, []]
        self.h = 1
        self.n = 0

    # ------------------------------------------------------------ insert

    def _split_up(self, node, path):
        """node holds 17 entries; split it and propagate up the path."""
        while True:
            g1, b1, g2, b2 = _split(node[4])
            node[0], node[1], node[2], node[3] = b1
            node[4] = g1
            new = [b2[0], b2[1], b2[2], b2[3], g2]
            if path:
                parent = path.pop()
                pk = parent[4]
                pk.append(new)
                if len(pk) <= 16:
                    return
                node = parent
            else:
                self.root = [
                    b1[0] if b1[0] < b2[0] else b2[0],
                    b1[1] if b1[1] < b2[1] else b2[1],
                    b1[2] if b1[2] > b2[2] else b2[2],
                    b1[3] if b1[3] > b2[3] else b2[3],
                    [node, new],
                ]
                self.h += 1
                return

    def insert(self, x0: int, y0: int, x1: int, y1: int, id: int) -> None:
        entry = (x0, y0, x1, y1, id)
        if not self.n:
            self.root = [x0, y0, x1, y1, [entry]]
            self.h = 1
            self.n = 1
            return
        self.n += 1
        node = self.root
        path = []
        for _ in range(self.h - 1):
            if x0 < node[0]:
                node[0] = x0
            if y0 < node[1]:
                node[1] = y0
            if x1 > node[2]:
                node[2] = x1
            if y1 > node[3]:
                node[3] = y1
            path.append(node)
            kids = node[4]
            enl = [((c if c > x1 else x1) - (a if a < x0 else x0))
                   * ((d if d > y1 else y1) - (b if b < y0 else y0))
                   - (c - a) * (d - b)
                   for a, b, c, d, _ in kids]
            m = min(enl)
            j = enl.index(m)
            if enl.count(m) > 1:
                a, b, c, d, _ = kids[j]
                ba = (c - a) * (d - b)
                for jj in range(j + 1, len(kids)):
                    if enl[jj] == m:
                        a, b, c, d, _ = kids[jj]
                        ar = (c - a) * (d - b)
                        if ar < ba:
                            ba = ar
                            j = jj
            node = kids[j]
        if x0 < node[0]:
            node[0] = x0
        if y0 < node[1]:
            node[1] = y0
        if x1 > node[2]:
            node[2] = x1
        if y1 > node[3]:
            node[3] = y1
        kids = node[4]
        kids.append(entry)
        if len(kids) > 16:
            self._split_up(node, path)

    def _insert_entry(self, entry, hl):
        """Insert entry into a node at height hl (0 = leaf)."""
        x0, y0, x1, y1 = entry[0], entry[1], entry[2], entry[3]
        node = self.root
        path = []
        for _ in range(self.h - 1 - hl):
            if x0 < node[0]:
                node[0] = x0
            if y0 < node[1]:
                node[1] = y0
            if x1 > node[2]:
                node[2] = x1
            if y1 > node[3]:
                node[3] = y1
            path.append(node)
            kids = node[4]
            enl = [((c if c > x1 else x1) - (a if a < x0 else x0))
                   * ((d if d > y1 else y1) - (b if b < y0 else y0))
                   - (c - a) * (d - b)
                   for a, b, c, d, _ in kids]
            m = min(enl)
            j = enl.index(m)
            if enl.count(m) > 1:
                a, b, c, d, _ = kids[j]
                ba = (c - a) * (d - b)
                for jj in range(j + 1, len(kids)):
                    if enl[jj] == m:
                        a, b, c, d, _ = kids[jj]
                        ar = (c - a) * (d - b)
                        if ar < ba:
                            ba = ar
                            j = jj
            node = kids[j]
        if x0 < node[0]:
            node[0] = x0
        if y0 < node[1]:
            node[1] = y0
        if x1 > node[2]:
            node[2] = x1
        if y1 > node[3]:
            node[3] = y1
        kids = node[4]
        kids.append(entry)
        if len(kids) > 16:
            self._split_up(node, path)

    # ------------------------------------------------------------ remove

    def remove(self, x0: int, y0: int, x1: int, y1: int, id: int) -> bool:
        if not self.n:
            return False
        t = (x0, y0, x1, y1, id)
        root = self.root
        h = self.h
        if h == 1:
            kids = root[4]
            if t not in kids:
                return False
            del kids[kids.index(t)]
            self.n -= 1
            if kids:
                a, b, c, d, _ = zip(*kids)
                root[0] = min(a)
                root[1] = min(b)
                root[2] = max(c)
                root[3] = max(d)
            return True

        # Find the leaf: depth-first over subtrees containing the rectangle.
        lp = h - 2  # path index of the parents of leaves
        nodes = [root]
        idxs = [0]
        k = 0
        leaf = None
        while True:
            kids = nodes[k][4]
            i = idxs[k]
            nk = len(kids)
            if k == lp:
                while i < nk:
                    c = kids[i]
                    i += 1
                    if (c[0] <= x0 and c[1] <= y0 and c[2] >= x1
                            and c[3] >= y1 and t in c[4]):
                        idxs[k] = i
                        leaf = c
                        break
                if leaf is not None:
                    break
            else:
                descended = False
                while i < nk:
                    c = kids[i]
                    i += 1
                    if c[0] <= x0 and c[1] <= y0 and c[2] >= x1 and c[3] >= y1:
                        idxs[k] = i
                        nodes.append(c)
                        idxs.append(0)
                        k += 1
                        descended = True
                        break
                if descended:
                    continue
            if k == 0:
                return False
            nodes.pop()
            idxs.pop()
            k -= 1

        lk = leaf[4]
        del lk[lk.index(t)]
        self.n -= 1

        # Condense the tree.
        orphans = None
        child = leaf
        ck = lk
        hl = 0
        while k >= 0:
            parent = nodes[k]
            if len(ck) < 6:
                del parent[4][idxs[k] - 1]
                if orphans is None:
                    orphans = [(hl, ck)]
                else:
                    orphans.append((hl, ck))
            else:
                a, b, c, d, _ = zip(*ck)
                a = min(a)
                b = min(b)
                c = max(c)
                d = max(d)
                if (child[0] == a and child[1] == b and child[2] == c
                        and child[3] == d):
                    break
                child[0] = a
                child[1] = b
                child[2] = c
                child[3] = d
            child = parent
            ck = parent[4]
            k -= 1
            hl += 1
        else:
            # child is the root, which always keeps at least one entry here.
            a, b, c, d, _ = zip(*ck)
            child[0] = min(a)
            child[1] = min(b)
            child[2] = max(c)
            child[3] = max(d)

        if orphans is not None:
            ins = self._insert_entry
            for hl, ek in orphans:
                for e in ek:
                    ins(e, hl)
            root = self.root
            while self.h > 1 and len(root[4]) == 1:
                root = root[4][0]
                self.h -= 1
            self.root = root
        return True

    # ------------------------------------------------------------ queries

    def search(self, x0: int, y0: int, x1: int, y1: int, out: list, cap: int) -> int:
        lvl = [self.root[4]]
        for _ in range(self.h - 1):
            lvl = [ch for ks in lvl for a, b, c, d, ch in ks
                   if a <= x1 and x0 <= c and b <= y1 and y0 <= d]
        res = [i for ks in lvl for a, b, c, d, i in ks
               if a <= x1 and x0 <= c and b <= y1 and y0 <= d]
        total = len(res)
        if total <= cap:
            out[:total] = res
        else:
            out[:cap] = res[:cap]
        return total

    def nearest(self, x: int, y: int, k: int, out: list) -> int:
        n = self.n
        if k > n:
            k = n
        if k <= 0:
            return 0
        worst = _INF
        best = []
        heap = []
        cnt = 0
        node = self.root[4]
        hl = self.h - 1
        while True:
            if hl == 0:
                best += [(((dx := (a - x if x < a else (x - c if x > c else 0))) * dx
                           + (dy := (b - y if y < b else (y - d if y > d else 0))) * dy)
                          << 31) | i
                         for a, b, c, d, i in node]
                best.sort()
                if len(best) >= k:
                    del best[k:]
                    worst = best[-1]
            else:
                hl1 = hl - 1
                for a, b, c, d, ch in node:
                    dx = a - x if x < a else (x - c if x > c else 0)
                    dy = b - y if y < b else (y - d if y > d else 0)
                    key = (dx * dx + dy * dy) << 31
                    if key < worst:
                        cnt += 1
                        heappush(heap, (key, cnt, ch, hl1))
            if not heap or heap[0][0] >= worst:
                break
            _, _, node, hl = heappop(heap)
        out[:k] = [v & _IDMASK for v in best]
        return k

    # ------------------------------------------------------------ misc

    def __len__(self) -> int:
        return self.n

    def height(self) -> int:
        return self.h if self.n else 0

    def node_count(self) -> int:
        if not self.n:
            return 0
        total = 1
        lvl = [self.root]
        for _ in range(self.h - 1):
            lvl = [ch for nd in lvl for ch in nd[4]]
            total += len(lvl)
        return total
