import java.util.Arrays;

public final class RTree {

    private static final int MAX_ENTRIES = 16;
    private static final int MIN_ENTRIES = 6;
    private static final int MAX_COORD = 0xFFFFF;
    private static final long COORD_MASK = 0xFFFFFL;
    private static final long GUARD = (1L << 20) | (1L << 41) | (1L << 62);

    // Each node holds 16 entries * 2 longs = 32 longs = 256 bytes (2 M3 cache lines).
    // Padding by 14 longs (112 bytes) aligns node 0 to a 128-byte cache-line boundary
    // on standard 16-byte Java array headers for page-aligned arrays.
    private static final int NODE_LONGS_SHIFT = 5;
    private static final int POOL_PAD = 14;
    private static final int INITIAL_POOL_CAP = 32;

    // Flat node pool:
    //   w0 = x0 | (y0 << 21) | ((MAX_COORD - x1) << 42)
    //   w1 = (y1 << 42) | val   (val is entry id in leaves, child node index in internal nodes)
    private long[] pool;
    private byte[] counts;
    private int poolCap;
    private int allocated;
    private int freeHead;

    private int root;
    private int height;
    private int size;
    private int liveNodes;

    // Reusable scratch buffers for insert, split, remove, search, nearest.
    private final int[] pathNode = new int[32];
    private final int[] pathSlot = new int[32];

    private final int[] sx0 = new int[17];
    private final int[] sy0 = new int[17];
    private final int[] sx1 = new int[17];
    private final int[] sy1 = new int[17];
    private final long[] sw0 = new long[17];
    private final long[] sw1 = new long[17];
    private final long[] sArea = new long[17];
    private final int[] sRem = new int[17];
    private final long[] sD1 = new long[17];
    private final long[] sD2 = new long[17];

    private long splitG1W0, splitG1W1;
    private long splitG2W0, splitG2W1;
    private int splitG2X0, splitG2Y0, splitG2X1, splitG2Y1;

    private final long[] reinsertW0 = new long[128];
    private final long[] reinsertW1 = new long[128];
    private final byte[] reinsertLevel = new byte[128];

    private final int[] searchStack = new int[512];

    // Lazily allocated scratch buffers for nearest().
    private long[] pqDist;
    private int[] pqNode;
    private long[] resDist;
    private int[] resId;

    public RTree() {
        this.poolCap = INITIAL_POOL_CAP;
        this.pool = new long[(INITIAL_POOL_CAP << NODE_LONGS_SHIFT) + POOL_PAD];
        this.counts = new byte[INITIAL_POOL_CAP];
        this.allocated = 0;
        this.freeHead = -1;
        this.root = -1;
        this.height = 0;
        this.size = 0;
        this.liveNodes = 0;
    }

    private static long packW0(int x0, int y0, int x1) {
        return (long) x0 | ((long) y0 << 21) | ((long) (MAX_COORD - x1) << 42);
    }

    private static long packW1(int y1, int val) {
        return ((long) y1 << 42) | (long) val;
    }

    private int allocNode() {
        int u = freeHead;
        if (u >= 0) {
            freeHead = (int) pool[(u << NODE_LONGS_SHIFT) + POOL_PAD];
        } else {
            if (allocated == poolCap) {
                growPool();
            }
            u = allocated++;
        }
        counts[u] = 0;
        liveNodes++;
        return u;
    }

    private void freeNode(int u) {
        pool[(u << NODE_LONGS_SHIFT) + POOL_PAD] = freeHead;
        freeHead = u;
        liveNodes--;
    }

    private void growPool() {
        int newCap = poolCap << 1;
        pool = Arrays.copyOf(pool, (newCap << NODE_LONGS_SHIFT) + POOL_PAD);
        counts = Arrays.copyOf(counts, newCap);
        poolCap = newCap;
    }

    public int size() {
        return size;
    }

    public int height() {
        return height;
    }

    public int nodeCount() {
        return liveNodes;
    }

    // ------------------------------------------------------------ insert

    public void insert(int x0, int y0, int x1, int y1, int id) {
        if (root < 0) {
            int r = allocNode();
            root = r;
            height = 1;
            int off = (r << NODE_LONGS_SHIFT) + POOL_PAD;
            pool[off] = packW0(x0, y0, x1);
            pool[off + 1] = packW1(y1, id);
            counts[r] = 1;
            size = 1;
            return;
        }
        insertAtLevel(x0, y0, x1, y1, id, 0);
        size++;
    }

    private void insertAtLevel(int x0, int y0, int x1, int y1, int val, int targetLevel) {
        int cur = root;
        int curLevel = height - 1;
        int depth = 0;

        long[] pool = this.pool;
        byte[] counts = this.counts;
        final int[] pNode = this.pathNode;
        final int[] pSlot = this.pathSlot;

        // 1. Choose subtree down to targetLevel.
        while (curLevel > targetLevel) {
            int base = (cur << NODE_LONGS_SHIFT) + POOL_PAD;
            int end = base + (counts[cur] << 1);
            long bestEnl = Long.MAX_VALUE;
            long bestArea = Long.MAX_VALUE;
            int bestSlot = 0;
            int bestChild = 0;

            for (int p = base, slot = 0; p < end; p += 2, slot++) {
                long w0 = pool[p];
                long w1 = pool[p + 1];
                int ex0 = (int) (w0 & COORD_MASK);
                int ey0 = (int) ((w0 >>> 21) & COORD_MASK);
                int ex1 = MAX_COORD - (int) (w0 >>> 42);
                int ey1 = (int) (w1 >>> 42);

                long oldArea = (long) (ex1 - ex0) * (ey1 - ey0);
                int nx0 = Math.min(ex0, x0);
                int ny0 = Math.min(ey0, y0);
                int nx1 = Math.max(ex1, x1);
                int ny1 = Math.max(ey1, y1);
                long enl = (long) (nx1 - nx0) * (ny1 - ny0) - oldArea;

                if (enl <= bestEnl) {
                    if (enl < bestEnl || oldArea < bestArea) {
                        bestEnl = enl;
                        bestArea = oldArea;
                        bestSlot = slot;
                        bestChild = (int) w1;
                    }
                }
            }

            pNode[depth] = cur;
            pSlot[depth] = bestSlot;
            depth++;
            cur = bestChild;
            curLevel--;
        }

        // 2. Insert into cur, or split if full.
        int c = counts[cur];
        if (c < MAX_ENTRIES) {
            int p = (cur << NODE_LONGS_SHIFT) + POOL_PAD + (c << 1);
            pool[p] = packW0(x0, y0, x1);
            pool[p + 1] = packW1(y1, val);
            counts[cur] = (byte) (c + 1);
            if (depth > 0) {
                propagateUnion(x0, y0, x1, y1, depth);
            }
            return;
        }

        // Split cur with the 17th entry (x0, y0, x1, y1, val).
        int splitNode = splitQuadratic(cur, x0, y0, x1, y1, val);
        // Re-fetch pool/counts in case splitQuadratic grew the pool.
        pool = this.pool;
        counts = this.counts;

        // 3. Adjust tree upwards.
        for (int d = depth - 1; d >= 0; d--) {
            int parent = pNode[d];
            int slot = pSlot[d];
            int pOff = (parent << NODE_LONGS_SHIFT) + POOL_PAD;
            int slotOff = pOff + (slot << 1);

            // Update existing child's MBR to group 1's exact MBR.
            pool[slotOff] = splitG1W0;
            pool[slotOff + 1] = splitG1W1;

            int pc = counts[parent];
            if (pc < MAX_ENTRIES) {
                int newOff = pOff + (pc << 1);
                pool[newOff] = splitG2W0;
                pool[newOff + 1] = splitG2W1;
                counts[parent] = (byte) (pc + 1);
                if (d > 0) {
                    propagateUnion(x0, y0, x1, y1, d);
                }
                return;
            }

            // Parent also overflows: split it with group 2 as the 17th entry.
            splitNode = splitQuadratic(parent, splitG2X0, splitG2Y0, splitG2X1, splitG2Y1, splitNode);
            pool = this.pool;
            counts = this.counts;
        }

        // 4. Root was split: create new root.
        int newRoot = allocNode();
        pool = this.pool;
        counts = this.counts;
        int rOff = (newRoot << NODE_LONGS_SHIFT) + POOL_PAD;
        pool[rOff] = splitG1W0;
        pool[rOff + 1] = splitG1W1;
        pool[rOff + 2] = splitG2W0;
        pool[rOff + 3] = splitG2W1;
        counts[newRoot] = 2;
        root = newRoot;
        height++;
    }

    private void propagateUnion(int x0, int y0, int x1, int y1, int depth) {
        final long[] pool = this.pool;
        final int[] pNode = this.pathNode;
        final int[] pSlot = this.pathSlot;
        final long insCont = GUARD | (long) x0 | ((long) y0 << 21) | ((long) (MAX_COORD - x1) << 42);
        final long y1Shift = (long) y1 << 42;

        for (int d = depth - 1; d >= 0; d--) {
            int pOff = (pNode[d] << NODE_LONGS_SHIFT) + POOL_PAD + (pSlot[d] << 1);
            long pw0 = pool[pOff];
            long pw1 = pool[pOff + 1];
            if ((((insCont - pw0) & GUARD) == GUARD) & (pw1 >= y1Shift)) {
                return;
            }
            int ex0 = (int) (pw0 & COORD_MASK);
            int ey0 = (int) ((pw0 >>> 21) & COORD_MASK);
            int ex1 = MAX_COORD - (int) (pw0 >>> 42);
            int ey1 = (int) (pw1 >>> 42);
            int nx0 = Math.min(ex0, x0);
            int ny0 = Math.min(ey0, y0);
            int nx1 = Math.max(ex1, x1);
            pool[pOff] = packW0(nx0, ny0, nx1);
            if (y1 > ey1) {
                pool[pOff + 1] = packW1(y1, (int) pw1);
            }
        }
    }

    private int splitQuadratic(int node1, int ax0, int ay0, int ax1, int ay1, int aval) {
        // Allocate node2 BEFORE caching this.pool / this.counts!
        int node2 = allocNode();
        final long[] pool = this.pool;
        final byte[] counts = this.counts;

        final int[] sx0 = this.sx0;
        final int[] sy0 = this.sy0;
        final int[] sx1 = this.sx1;
        final int[] sy1 = this.sy1;
        final long[] sw0 = this.sw0;
        final long[] sw1 = this.sw1;
        final long[] sArea = this.sArea;

        int off1 = (node1 << NODE_LONGS_SHIFT) + POOL_PAD;
        for (int i = 0; i < MAX_ENTRIES; i++) {
            long w0 = pool[off1 + (i << 1)];
            long w1 = pool[off1 + (i << 1) + 1];
            sw0[i] = w0;
            sw1[i] = w1;
            int ex0 = (int) (w0 & COORD_MASK);
            int ey0 = (int) ((w0 >>> 21) & COORD_MASK);
            int ex1 = MAX_COORD - (int) (w0 >>> 42);
            int ey1 = (int) (w1 >>> 42);
            sx0[i] = ex0;
            sy0[i] = ey0;
            sx1[i] = ex1;
            sy1[i] = ey1;
            sArea[i] = (long) (ex1 - ex0) * (ey1 - ey0);
        }
        sw0[16] = packW0(ax0, ay0, ax1);
        sw1[16] = packW1(ay1, aval);
        sx0[16] = ax0;
        sy0[16] = ay0;
        sx1[16] = ax1;
        sy1[16] = ay1;
        sArea[16] = (long) (ax1 - ax0) * (ay1 - ay0);

        // PickSeeds: pair maximizing area(J) - area(E1) - area(E2).
        long bestD = Long.MIN_VALUE;
        int seed1 = 0;
        int seed2 = 1;
        for (int i = 0; i < 16; i++) {
            int ix0 = sx0[i], iy0 = sy0[i], ix1 = sx1[i], iy1 = sy1[i];
            long iArea = sArea[i];
            for (int j = i + 1; j < 17; j++) {
                int jx0 = Math.min(ix0, sx0[j]);
                int jy0 = Math.min(iy0, sy0[j]);
                int jx1 = Math.max(ix1, sx1[j]);
                int jy1 = Math.max(iy1, sy1[j]);
                long d = (long) (jx1 - jx0) * (jy1 - jy0) - iArea - sArea[j];
                if (d > bestD) {
                    bestD = d;
                    seed1 = i;
                    seed2 = j;
                }
            }
        }

        int off2 = (node2 << NODE_LONGS_SHIFT) + POOL_PAD;
        pool[off1] = sw0[seed1];
        pool[off1 + 1] = sw1[seed1];
        pool[off2] = sw0[seed2];
        pool[off2 + 1] = sw1[seed2];

        int g1x0 = sx0[seed1], g1y0 = sy0[seed1], g1x1 = sx1[seed1], g1y1 = sy1[seed1];
        int g2x0 = sx0[seed2], g2y0 = sy0[seed2], g2x1 = sx1[seed2], g2y1 = sy1[seed2];
        long g1Area = sArea[seed1];
        long g2Area = sArea[seed2];
        int g1Count = 1;
        int g2Count = 1;

        final int[] rem = this.sRem;
        final long[] d1Arr = this.sD1;
        final long[] d2Arr = this.sD2;
        int remCount = 0;
        for (int i = 0; i < 17; i++) {
            if (i == seed1 || i == seed2) continue;
            rem[remCount++] = i;
            int rx0 = sx0[i], ry0 = sy0[i], rx1 = sx1[i], ry1 = sy1[i];
            int ux0 = g1x0 < rx0 ? g1x0 : rx0;
            int uy0 = g1y0 < ry0 ? g1y0 : ry0;
            int ux1 = g1x1 > rx1 ? g1x1 : rx1;
            int uy1 = g1y1 > ry1 ? g1y1 : ry1;
            d1Arr[i] = (long) (ux1 - ux0) * (uy1 - uy0) - g1Area;

            ux0 = g2x0 < rx0 ? g2x0 : rx0;
            uy0 = g2y0 < ry0 ? g2y0 : ry0;
            ux1 = g2x1 > rx1 ? g2x1 : rx1;
            uy1 = g2y1 > ry1 ? g2y1 : ry1;
            d2Arr[i] = (long) (ux1 - ux0) * (uy1 - uy0) - g2Area;
        }

        // Assign remaining entries.
        while (remCount > 0) {
            if (g1Count + remCount == MIN_ENTRIES) {
                for (int k = 0; k < remCount; k++) {
                    int idx = rem[k];
                    int p = off1 + (g1Count << 1);
                    pool[p] = sw0[idx];
                    pool[p + 1] = sw1[idx];
                    g1Count++;
                    if (sx0[idx] < g1x0) g1x0 = sx0[idx];
                    if (sy0[idx] < g1y0) g1y0 = sy0[idx];
                    if (sx1[idx] > g1x1) g1x1 = sx1[idx];
                    if (sy1[idx] > g1y1) g1y1 = sy1[idx];
                }
                break;
            }
            if (g2Count + remCount == MIN_ENTRIES) {
                for (int k = 0; k < remCount; k++) {
                    int idx = rem[k];
                    int p = off2 + (g2Count << 1);
                    pool[p] = sw0[idx];
                    pool[p + 1] = sw1[idx];
                    g2Count++;
                    if (sx0[idx] < g2x0) g2x0 = sx0[idx];
                    if (sy0[idx] < g2y0) g2y0 = sy0[idx];
                    if (sx1[idx] > g2x1) g2x1 = sx1[idx];
                    if (sy1[idx] > g2y1) g2y1 = sy1[idx];
                }
                break;
            }

            // PickNext: largest |d1 - d2|.
            int bestPos = 0;
            long bestDiff = -1L;
            for (int k = 0; k < remCount; k++) {
                int idx = rem[k];
                long diff = d1Arr[idx] - d2Arr[idx];
                if (diff < 0) diff = -diff;
                if (diff > bestDiff) {
                    bestDiff = diff;
                    bestPos = k;
                }
            }

            int idx = rem[bestPos];
            rem[bestPos] = rem[--remCount];

            long d1 = d1Arr[idx];
            long d2 = d2Arr[idx];
            boolean toGroup1;
            if (d1 != d2) {
                toGroup1 = d1 < d2;
            } else if (g1Area != g2Area) {
                toGroup1 = g1Area < g2Area;
            } else {
                toGroup1 = g1Count <= g2Count;
            }

            int rx0 = sx0[idx], ry0 = sy0[idx], rx1 = sx1[idx], ry1 = sy1[idx];
            if (toGroup1) {
                int p = off1 + (g1Count << 1);
                pool[p] = sw0[idx];
                pool[p + 1] = sw1[idx];
                g1Count++;
                if (rx0 < g1x0 || ry0 < g1y0 || rx1 > g1x1 || ry1 > g1y1) {
                    if (rx0 < g1x0) g1x0 = rx0;
                    if (ry0 < g1y0) g1y0 = ry0;
                    if (rx1 > g1x1) g1x1 = rx1;
                    if (ry1 > g1y1) g1y1 = ry1;
                    g1Area = (long) (g1x1 - g1x0) * (g1y1 - g1y0);
                    for (int k = 0; k < remCount; k++) {
                        int r = rem[k];
                        int ux0 = g1x0 < sx0[r] ? g1x0 : sx0[r];
                        int uy0 = g1y0 < sy0[r] ? g1y0 : sy0[r];
                        int ux1 = g1x1 > sx1[r] ? g1x1 : sx1[r];
                        int uy1 = g1y1 > sy1[r] ? g1y1 : sy1[r];
                        d1Arr[r] = (long) (ux1 - ux0) * (uy1 - uy0) - g1Area;
                    }
                }
            } else {
                int p = off2 + (g2Count << 1);
                pool[p] = sw0[idx];
                pool[p + 1] = sw1[idx];
                g2Count++;
                if (rx0 < g2x0 || ry0 < g2y0 || rx1 > g2x1 || ry1 > g2y1) {
                    if (rx0 < g2x0) g2x0 = rx0;
                    if (ry0 < g2y0) g2y0 = ry0;
                    if (rx1 > g2x1) g2x1 = rx1;
                    if (ry1 > g2y1) g2y1 = ry1;
                    g2Area = (long) (g2x1 - g2x0) * (g2y1 - g2y0);
                    for (int k = 0; k < remCount; k++) {
                        int r = rem[k];
                        int ux0 = g2x0 < sx0[r] ? g2x0 : sx0[r];
                        int uy0 = g2y0 < sy0[r] ? g2y0 : sy0[r];
                        int ux1 = g2x1 > sx1[r] ? g2x1 : sx1[r];
                        int uy1 = g2y1 > sy1[r] ? g2y1 : sy1[r];
                        d2Arr[r] = (long) (ux1 - ux0) * (uy1 - uy0) - g2Area;
                    }
                }
            }
        }

        counts[node1] = (byte) g1Count;
        counts[node2] = (byte) g2Count;

        splitG1W0 = packW0(g1x0, g1y0, g1x1);
        splitG1W1 = packW1(g1y1, node1);
        splitG2W0 = packW0(g2x0, g2y0, g2x1);
        splitG2W1 = packW1(g2y1, node2);
        splitG2X0 = g2x0;
        splitG2Y0 = g2y0;
        splitG2X1 = g2x1;
        splitG2Y1 = g2y1;
        return node2;
    }

    // ------------------------------------------------------------ remove

    public boolean remove(int rx0, int ry0, int rx1, int ry1, int id) {
        if (root < 0) return false;

        final long[] pool = this.pool;
        final byte[] counts = this.counts;
        final long targetW0 = packW0(rx0, ry0, rx1);
        final long targetW1 = packW1(ry1, id);

        if (height == 1) {
            int r = root;
            int c = counts[r];
            int base = (r << NODE_LONGS_SHIFT) + POOL_PAD;
            for (int i = 0; i < c; i++) {
                int p = base + (i << 1);
                if (pool[p] == targetW0 && pool[p + 1] == targetW1) {
                    int last = c - 1;
                    if (i != last) {
                        int lp = base + (last << 1);
                        pool[p] = pool[lp];
                        pool[p + 1] = pool[lp + 1];
                    }
                    counts[r] = (byte) last;
                    size--;
                    if (last == 0) {
                        freeNode(r);
                        root = -1;
                        height = 0;
                    }
                    return true;
                }
            }
            return false;
        }

        // 1. FindLeaf via iterative DFS, recording pathNode[0..height-1] and pathSlot[0..height-2].
        final int[] pNode = this.pathNode;
        final int[] pSlot = this.pathSlot;
        final long rCont = GUARD | (long) rx0 | ((long) ry0 << 21) | ((long) (MAX_COORD - rx1) << 42);
        final long ry1Shift = (long) ry1 << 42;
        final int leafDepth = height - 1;

        int depth = 0;
        pNode[0] = root;
        pSlot[0] = 0;
        int leafSlot = -1;

        while (depth >= 0) {
            int u = pNode[depth];
            int c = counts[u];
            int base = (u << NODE_LONGS_SHIFT) + POOL_PAD;

            if (depth == leafDepth) {
                for (int i = 0; i < c; i++) {
                    int p = base + (i << 1);
                    if (pool[p] == targetW0 && pool[p + 1] == targetW1) {
                        leafSlot = i;
                        break;
                    }
                }
                if (leafSlot >= 0) break;
                depth--;
                if (depth >= 0) pSlot[depth]++;
            } else {
                int s = pSlot[depth];
                boolean descended = false;
                while (s < c) {
                    int p = base + (s << 1);
                    long w0 = pool[p];
                    long w1 = pool[p + 1];
                    if ((((rCont - w0) & GUARD) == GUARD) & (w1 >= ry1Shift)) {
                        pSlot[depth] = s;
                        depth++;
                        pNode[depth] = (int) w1;
                        pSlot[depth] = 0;
                        descended = true;
                        break;
                    }
                    s++;
                }
                if (!descended) {
                    depth--;
                    if (depth >= 0) pSlot[depth]++;
                }
            }
        }

        if (leafSlot < 0) return false;

        // 2. Remove entry from leaf.
        int leaf = pNode[leafDepth];
        int lc = counts[leaf] - 1;
        int lBase = (leaf << NODE_LONGS_SHIFT) + POOL_PAD;
        if (leafSlot != lc) {
            int dst = lBase + (leafSlot << 1);
            int src = lBase + (lc << 1);
            pool[dst] = pool[src];
            pool[dst + 1] = pool[src + 1];
        }
        counts[leaf] = (byte) lc;
        size--;

        // 3. CondenseTree walking up from leaf to root's child.
        final long[] rW0 = this.reinsertW0;
        final long[] rW1 = this.reinsertW1;
        final byte[] rLvl = this.reinsertLevel;
        int reinsertCount = 0;

        boolean childRemoved = true;
        int prevOldX0 = rx0, prevOldY0 = ry0, prevOldX1 = rx1, prevOldY1 = ry1;
        int prevNewX0 = 0, prevNewY0 = 0, prevNewX1 = 0, prevNewY1 = 0;

        for (int d = leafDepth; d >= 1; d--) {
            int u = pNode[d];
            int parent = pNode[d - 1];
            int slot = pSlot[d - 1];
            int pBase = (parent << NODE_LONGS_SHIFT) + POOL_PAD;
            int pSlotOff = pBase + (slot << 1);

            long oldW0 = pool[pSlotOff];
            long oldW1 = pool[pSlotOff + 1];
            int oldX0 = (int) (oldW0 & COORD_MASK);
            int oldY0 = (int) ((oldW0 >>> 21) & COORD_MASK);
            int oldX1 = MAX_COORD - (int) (oldW0 >>> 42);
            int oldY1 = (int) (oldW1 >>> 42);

            int uc = counts[u];
            if (uc < MIN_ENTRIES) {
                // Eliminate u: set aside its entries and remove u from parent.
                byte lvl = (byte) (leafDepth - d);
                int uBase = (u << NODE_LONGS_SHIFT) + POOL_PAD;
                for (int i = 0; i < uc; i++) {
                    rW0[reinsertCount] = pool[uBase + (i << 1)];
                    rW1[reinsertCount] = pool[uBase + (i << 1) + 1];
                    rLvl[reinsertCount] = lvl;
                    reinsertCount++;
                }
                freeNode(u);

                int pc = counts[parent] - 1;
                if (slot != pc) {
                    int src = pBase + (pc << 1);
                    pool[pSlotOff] = pool[src];
                    pool[pSlotOff + 1] = pool[src + 1];
                }
                counts[parent] = (byte) pc;

                childRemoved = true;
                prevOldX0 = oldX0;
                prevOldY0 = oldY0;
                prevOldX1 = oldX1;
                prevOldY1 = oldY1;
            } else {
                // Check if u's MBR could possibly have shrunk.
                if (childRemoved) {
                    if (prevOldX0 > oldX0 && prevOldY0 > oldY0 && prevOldX1 < oldX1 && prevOldY1 < oldY1) {
                        break;
                    }
                } else {
                    if ((prevOldX0 > oldX0 || prevNewX0 == prevOldX0)
                            && (prevOldY0 > oldY0 || prevNewY0 == prevOldY0)
                            && (prevOldX1 < oldX1 || prevNewX1 == prevOldX1)
                            && (prevOldY1 < oldY1 || prevNewY1 == prevOldY1)) {
                        break;
                    }
                }

                // Recompute exact MBR of u.
                int uBase = (u << NODE_LONGS_SHIFT) + POOL_PAD;
                int uEnd = uBase + (uc << 1);
                int nx0 = MAX_COORD, ny0 = MAX_COORD, minInvX1 = MAX_COORD, ny1 = 0;
                for (int p = uBase; p < uEnd; p += 2) {
                    long w0 = pool[p];
                    long w1 = pool[p + 1];
                    int ex0 = (int) (w0 & COORD_MASK);
                    int ey0 = (int) ((w0 >>> 21) & COORD_MASK);
                    int invX1 = (int) (w0 >>> 42);
                    int ey1 = (int) (w1 >>> 42);
                    if (ex0 < nx0) nx0 = ex0;
                    if (ey0 < ny0) ny0 = ey0;
                    if (invX1 < minInvX1) minInvX1 = invX1;
                    if (ey1 > ny1) ny1 = ey1;
                }
                int nx1 = MAX_COORD - minInvX1;

                if (nx0 == oldX0 && ny0 == oldY0 && nx1 == oldX1 && ny1 == oldY1) {
                    break;
                }

                pool[pSlotOff] = packW0(nx0, ny0, nx1);
                pool[pSlotOff + 1] = packW1(ny1, u);

                childRemoved = false;
                prevOldX0 = oldX0;
                prevOldY0 = oldY0;
                prevOldX1 = oldX1;
                prevOldY1 = oldY1;
                prevNewX0 = nx0;
                prevNewY0 = ny0;
                prevNewX1 = nx1;
                prevNewY1 = ny1;
            }
        }

        // Reinsert set-aside entries (higher levels first).
        for (int i = reinsertCount - 1; i >= 0; i--) {
            long w0 = rW0[i];
            long w1 = rW1[i];
            int ex0 = (int) (w0 & COORD_MASK);
            int ey0 = (int) ((w0 >>> 21) & COORD_MASK);
            int ex1 = MAX_COORD - (int) (w0 >>> 42);
            int ey1 = (int) (w1 >>> 42);
            int val = (int) w1;
            insertAtLevel(ex0, ey0, ex1, ey1, val, rLvl[i]);
        }

        // 4. Shrink root while internal root has only 1 child.
        while (height > 1 && this.counts[root] == 1) {
            int oldRoot = root;
            root = (int) this.pool[(oldRoot << NODE_LONGS_SHIFT) + POOL_PAD + 1];
            freeNode(oldRoot);
            height--;
        }

        return true;
    }

    // ------------------------------------------------------------ search

    public int search(int qx0, int qy0, int qx1, int qy1, int[] outIds, int cap) {
        if (root < 0) return 0;
        if (qx0 == qx1 && qy0 == qy1) {
            return searchPoint(qx0, qy0, outIds, cap);
        }

        final long[] pool = this.pool;
        final byte[] counts = this.counts;
        final long qInter = GUARD | (long) qx1 | ((long) qy1 << 21) | ((long) (MAX_COORD - qx0) << 42);
        final long qy0Shift = (long) qy0 << 42;
        final long qInner = (long) qx0 | ((long) qy0 << 21) | ((long) (MAX_COORD - qx1) << 42);
        final long qy1Limit = (long) (qy1 + 1) << 42;

        if (height == 1) {
            int total = 0;
            int base = (root << NODE_LONGS_SHIFT) + POOL_PAD;
            int end = base + (counts[root] << 1);
            for (int p = base; p < end; p += 2) {
                long w0 = pool[p];
                long w1 = pool[p + 1];
                if ((((qInter - w0) & GUARD) == GUARD) & (w1 >= qy0Shift)) {
                    if (total < cap) outIds[total] = (int) w1;
                    total++;
                }
            }
            return total;
        }

        final int[] stack = this.searchStack;
        int sp = 0;
        stack[sp++] = root | ((height - 1) << 24);
        int total = 0;

        while (sp > 0) {
            int item = stack[--sp];
            int level = item >>> 24;
            int u = item & 0x00FFFFFF;
            int base = (u << NODE_LONGS_SHIFT) + POOL_PAD;
            int end = base + (counts[u] << 1);

            if (level == 1) {
                for (int p = base; p < end; p += 2) {
                    long w0 = pool[p];
                    long w1 = pool[p + 1];
                    if ((((qInter - w0) & GUARD) == GUARD) & (w1 >= qy0Shift)) {
                        int leaf = (int) w1;
                        int lc = counts[leaf];
                        if (((((w0 | GUARD) - qInner) & GUARD) == GUARD) & (w1 < qy1Limit)) {
                            if (total < cap) {
                                int take = cap - total;
                                if (lc < take) take = lc;
                                int lbase = (leaf << NODE_LONGS_SHIFT) + POOL_PAD + 1;
                                for (int j = 0; j < take; j++) {
                                    outIds[total + j] = (int) pool[lbase + (j << 1)];
                                }
                            }
                            total += lc;
                        } else {
                            int lbase = (leaf << NODE_LONGS_SHIFT) + POOL_PAD;
                            int lend = lbase + (lc << 1);
                            for (int lp = lbase; lp < lend; lp += 2) {
                                long lw0 = pool[lp];
                                long lw1 = pool[lp + 1];
                                if ((((qInter - lw0) & GUARD) == GUARD) & (lw1 >= qy0Shift)) {
                                    if (total < cap) outIds[total] = (int) lw1;
                                    total++;
                                }
                            }
                        }
                    }
                }
            } else {
                int childLevel = level - 1;
                int childLevelShift = childLevel << 24;
                for (int p = base; p < end; p += 2) {
                    long w0 = pool[p];
                    long w1 = pool[p + 1];
                    if ((((qInter - w0) & GUARD) == GUARD) & (w1 >= qy0Shift)) {
                        int child = (int) w1;
                        if (((((w0 | GUARD) - qInner) & GUARD) == GUARD) & (w1 < qy1Limit)) {
                            total = collectInternal(child, childLevel, outIds, cap, total);
                        } else {
                            stack[sp++] = child | childLevelShift;
                        }
                    }
                }
            }
        }
        return total;
    }

    private int searchPoint(int px, int py, int[] outIds, int cap) {
        final long[] pool = this.pool;
        final byte[] counts = this.counts;
        final long qInter = GUARD | (long) px | ((long) py << 21) | ((long) (MAX_COORD - px) << 42);
        final long pyShift = (long) py << 42;

        if (height == 1) {
            int total = 0;
            int base = (root << NODE_LONGS_SHIFT) + POOL_PAD;
            int end = base + (counts[root] << 1);
            for (int p = base; p < end; p += 2) {
                long w0 = pool[p];
                long w1 = pool[p + 1];
                if ((((qInter - w0) & GUARD) == GUARD) & (w1 >= pyShift)) {
                    if (total < cap) outIds[total] = (int) w1;
                    total++;
                }
            }
            return total;
        }

        final int[] stack = this.searchStack;
        int sp = 0;
        stack[sp++] = root | ((height - 1) << 24);
        int total = 0;

        while (sp > 0) {
            int item = stack[--sp];
            int level = item >>> 24;
            int u = item & 0x00FFFFFF;
            int base = (u << NODE_LONGS_SHIFT) + POOL_PAD;
            int end = base + (counts[u] << 1);

            if (level == 1) {
                for (int p = base; p < end; p += 2) {
                    long w0 = pool[p];
                    long w1 = pool[p + 1];
                    if ((((qInter - w0) & GUARD) == GUARD) & (w1 >= pyShift)) {
                        int leaf = (int) w1;
                        int lbase = (leaf << NODE_LONGS_SHIFT) + POOL_PAD;
                        int lend = lbase + (counts[leaf] << 1);
                        for (int lp = lbase; lp < lend; lp += 2) {
                            long lw0 = pool[lp];
                            long lw1 = pool[lp + 1];
                            if ((((qInter - lw0) & GUARD) == GUARD) & (lw1 >= pyShift)) {
                                if (total < cap) outIds[total] = (int) lw1;
                                total++;
                            }
                        }
                    }
                }
            } else {
                int childLevelShift = (level - 1) << 24;
                for (int p = base; p < end; p += 2) {
                    long w0 = pool[p];
                    long w1 = pool[p + 1];
                    if ((((qInter - w0) & GUARD) == GUARD) & (w1 >= pyShift)) {
                        stack[sp++] = ((int) w1) | childLevelShift;
                    }
                }
            }
        }
        return total;
    }

    private int collectInternal(int node, int level, int[] outIds, int cap, int total) {
        final long[] pool = this.pool;
        final byte[] counts = this.counts;
        int c = counts[node];
        int base = (node << NODE_LONGS_SHIFT) + POOL_PAD + 1;
        if (level == 1) {
            for (int i = 0; i < c; i++) {
                int leaf = (int) pool[base + (i << 1)];
                int lc = counts[leaf];
                if (total < cap) {
                    int take = cap - total;
                    if (lc < take) take = lc;
                    int lbase = (leaf << NODE_LONGS_SHIFT) + POOL_PAD + 1;
                    for (int j = 0; j < take; j++) {
                        outIds[total + j] = (int) pool[lbase + (j << 1)];
                    }
                }
                total += lc;
            }
        } else {
            int nextLevel = level - 1;
            for (int i = 0; i < c; i++) {
                int child = (int) pool[base + (i << 1)];
                total = collectInternal(child, nextLevel, outIds, cap, total);
            }
        }
        return total;
    }

    // ------------------------------------------------------------ nearest

    public int nearest(int px, int py, int k, int[] outIds) {
        if (k <= 0 || root < 0) return 0;
        int targetK = k < size ? k : size;
        if (targetK == 1) {
            return nearest1(px, py, outIds);
        }
        return nearestK(px, py, targetK, outIds);
    }

    private void ensurePqInit() {
        if (pqDist == null) {
            pqDist = new long[256];
            pqNode = new int[256];
        }
    }

    private void growPq() {
        int newCap = pqDist.length << 1;
        pqDist = Arrays.copyOf(pqDist, newCap);
        pqNode = Arrays.copyOf(pqNode, newCap);
    }

    private int pqPush(long dist, int nodeTagged, int pqSize) {
        if (pqSize == pqDist.length) {
            growPq();
        }
        final long[] pqD = this.pqDist;
        final int[] pqN = this.pqNode;
        int i = pqSize;
        while (i > 0) {
            int par = (i - 1) >>> 2;
            if (pqD[par] <= dist) break;
            pqD[i] = pqD[par];
            pqN[i] = pqN[par];
            i = par;
        }
        pqD[i] = dist;
        pqN[i] = nodeTagged;
        return pqSize + 1;
    }

    private int nearest1(int px, int py, int[] outIds) {
        final long[] pool = this.pool;
        final byte[] counts = this.counts;
        final int invPx = MAX_COORD - px;

        long bestDist = Long.MAX_VALUE;
        int bestId = Integer.MAX_VALUE;

        if (height == 1) {
            int base = (root << NODE_LONGS_SHIFT) + POOL_PAD;
            int end = base + (counts[root] << 1);
            for (int p = base; p < end; p += 2) {
                long w0 = pool[p];
                long w1 = pool[p + 1];
                int dx = Math.max(0, Math.max((int) (w0 & COORD_MASK) - px, (int) (w0 >>> 42) - invPx));
                int dy = Math.max(0, Math.max((int) ((w0 >>> 21) & COORD_MASK) - py, py - (int) (w1 >>> 42)));
                long dist = (long) dx * dx + (long) dy * dy;
                if (dist <= bestDist) {
                    int id = (int) w1;
                    if (dist < bestDist || id < bestId) {
                        bestDist = dist;
                        bestId = id;
                    }
                }
            }
            outIds[0] = bestId;
            return 1;
        }

        ensurePqInit();
        int pqSize = 0;

        int curNode = root;
        int curLevel = height - 1;

        while (true) {
            int base = (curNode << NODE_LONGS_SHIFT) + POOL_PAD;
            int end = base + (counts[curNode] << 1);
            int nextChild = -1;
            long nextChildDist = Long.MAX_VALUE;

            if (curLevel == 0) {
                for (int p = base; p < end; p += 2) {
                    long w0 = pool[p];
                    long w1 = pool[p + 1];
                    int dx = Math.max(0, Math.max((int) (w0 & COORD_MASK) - px, (int) (w0 >>> 42) - invPx));
                    int dy = Math.max(0, Math.max((int) ((w0 >>> 21) & COORD_MASK) - py, py - (int) (w1 >>> 42)));
                    long dist = (long) dx * dx + (long) dy * dy;
                    if (dist <= bestDist) {
                        int id = (int) w1;
                        if (dist < bestDist || id < bestId) {
                            bestDist = dist;
                            bestId = id;
                        }
                    }
                }
            } else if (curLevel == 1) {
                for (int p = base; p < end; p += 2) {
                    long w0 = pool[p];
                    long w1 = pool[p + 1];
                    int dx = Math.max(0, Math.max((int) (w0 & COORD_MASK) - px, (int) (w0 >>> 42) - invPx));
                    int dy = Math.max(0, Math.max((int) ((w0 >>> 21) & COORD_MASK) - py, py - (int) (w1 >>> 42)));
                    long dist = (long) dx * dx + (long) dy * dy;
                    if (dist > bestDist) continue;
                    int leaf = (int) w1;
                    if (dist == 0L) {
                        int lb = (leaf << NODE_LONGS_SHIFT) + POOL_PAD;
                        int le = lb + (counts[leaf] << 1);
                        for (int lp = lb; lp < le; lp += 2) {
                            long lw0 = pool[lp];
                            long lw1 = pool[lp + 1];
                            int ldx = Math.max(0, Math.max((int) (lw0 & COORD_MASK) - px, (int) (lw0 >>> 42) - invPx));
                            int ldy = Math.max(0, Math.max((int) ((lw0 >>> 21) & COORD_MASK) - py, py - (int) (lw1 >>> 42)));
                            long ldist = (long) ldx * ldx + (long) ldy * ldy;
                            if (ldist <= bestDist) {
                                int id = (int) lw1;
                                if (ldist < bestDist || id < bestId) {
                                    bestDist = ldist;
                                    bestId = id;
                                }
                            }
                        }
                    } else if (dist < nextChildDist) {
                        if (nextChild >= 0 && nextChildDist <= bestDist) {
                            pqSize = pqPush(nextChildDist, nextChild, pqSize);
                        }
                        nextChildDist = dist;
                        nextChild = leaf;
                    } else {
                        pqSize = pqPush(dist, leaf, pqSize);
                    }
                }
            } else {
                int childLevelShift = (curLevel - 1) << 24;
                for (int p = base; p < end; p += 2) {
                    long w0 = pool[p];
                    long w1 = pool[p + 1];
                    int dx = Math.max(0, Math.max((int) (w0 & COORD_MASK) - px, (int) (w0 >>> 42) - invPx));
                    int dy = Math.max(0, Math.max((int) ((w0 >>> 21) & COORD_MASK) - py, py - (int) (w1 >>> 42)));
                    long dist = (long) dx * dx + (long) dy * dy;
                    if (dist > bestDist) continue;
                    int childTagged = ((int) w1) | childLevelShift;
                    if (dist < nextChildDist) {
                        if (nextChild >= 0) {
                            pqSize = pqPush(nextChildDist, nextChild, pqSize);
                        }
                        nextChildDist = dist;
                        nextChild = childTagged;
                    } else {
                        pqSize = pqPush(dist, childTagged, pqSize);
                    }
                }
            }

            if (nextChild >= 0 && nextChildDist <= bestDist) {
                if (pqSize == 0 || nextChildDist <= this.pqDist[0]) {
                    curLevel = nextChild >>> 24;
                    curNode = nextChild & 0x00FFFFFF;
                    continue;
                }
                pqSize = pqPush(nextChildDist, nextChild, pqSize);
            }

            final long[] pqD = this.pqDist;
            if (pqSize == 0 || pqD[0] > bestDist) break;

            final int[] pqN = this.pqNode;
            int top = pqN[0];
            curLevel = top >>> 24;
            curNode = top & 0x00FFFFFF;

            int last = --pqSize;
            if (last > 0) {
                long moveD = pqD[last];
                int moveN = pqN[last];
                int i = 0;
                while (true) {
                    int c = (i << 2) + 1;
                    if (c >= last) break;
                    int best = c;
                    long minD = pqD[c];
                    int cEnd = c + 4;
                    if (cEnd > last) cEnd = last;
                    for (int j = c + 1; j < cEnd; j++) {
                        long d = pqD[j];
                        if (d < minD) {
                            minD = d;
                            best = j;
                        }
                    }
                    if (moveD <= minD) break;
                    pqD[i] = minD;
                    pqN[i] = pqN[best];
                    i = best;
                }
                pqD[i] = moveD;
                pqN[i] = moveN;
            }
        }

        outIds[0] = bestId;
        return 1;
    }

    private int nearestK(int px, int py, int targetK, int[] outIds) {
        final long[] pool = this.pool;
        final byte[] counts = this.counts;
        final int invPx = MAX_COORD - px;

        if (resDist == null || resDist.length < targetK) {
            int cap = Math.max(32, Integer.highestOneBit(targetK - 1) << 1);
            resDist = new long[cap];
            resId = new int[cap];
        }
        final long[] rDist = this.resDist;
        final int[] rId = this.resId;
        int found = 0;
        long thresholdDist = Long.MAX_VALUE;
        int thresholdId = Integer.MAX_VALUE;
        final int halfK = targetK >>> 1;

        if (height == 1) {
            int base = (root << NODE_LONGS_SHIFT) + POOL_PAD;
            int end = base + (counts[root] << 1);
            for (int p = base; p < end; p += 2) {
                long w0 = pool[p];
                long w1 = pool[p + 1];
                int dx = Math.max(0, Math.max((int) (w0 & COORD_MASK) - px, (int) (w0 >>> 42) - invPx));
                int dy = Math.max(0, Math.max((int) ((w0 >>> 21) & COORD_MASK) - py, py - (int) (w1 >>> 42)));
                long dist = (long) dx * dx + (long) dy * dy;
                int id = (int) w1;
                if (found < targetK) {
                    int i = found++;
                    while (i > 0) {
                        int par = (i - 1) >>> 1;
                        long pd = rDist[par];
                        int pid = rId[par];
                        if (pd > dist || (pd == dist && pid > id)) break;
                        rDist[i] = pd;
                        rId[i] = pid;
                        i = par;
                    }
                    rDist[i] = dist;
                    rId[i] = id;
                    if (found == targetK) {
                        thresholdDist = rDist[0];
                        thresholdId = rId[0];
                    }
                } else if (dist < thresholdDist || (dist == thresholdDist && id < thresholdId)) {
                    int i = 0;
                    while (i < halfK) {
                        int c = (i << 1) + 1;
                        long cd = rDist[c];
                        int cid = rId[c];
                        int r = c + 1;
                        if (r < targetK) {
                            long rd = rDist[r];
                            int rid = rId[r];
                            if (rd > cd || (rd == cd && rid > cid)) {
                                c = r;
                                cd = rd;
                                cid = rid;
                            }
                        }
                        if (dist > cd || (dist == cd && id > cid)) break;
                        rDist[i] = cd;
                        rId[i] = cid;
                        i = c;
                    }
                    rDist[i] = dist;
                    rId[i] = id;
                    thresholdDist = rDist[0];
                    thresholdId = rId[0];
                }
            }
            extractTopK(rDist, rId, found, outIds);
            return found;
        }

        ensurePqInit();
        int pqSize = 0;

        int curNode = root;
        int curLevel = height - 1;

        while (true) {
            int base = (curNode << NODE_LONGS_SHIFT) + POOL_PAD;
            int end = base + (counts[curNode] << 1);
            int nextChild = -1;
            long nextChildDist = Long.MAX_VALUE;

            if (curLevel == 0) {
                for (int p = base; p < end; p += 2) {
                    long w0 = pool[p];
                    long w1 = pool[p + 1];
                    int dx = Math.max(0, Math.max((int) (w0 & COORD_MASK) - px, (int) (w0 >>> 42) - invPx));
                    int dy = Math.max(0, Math.max((int) ((w0 >>> 21) & COORD_MASK) - py, py - (int) (w1 >>> 42)));
                    long dist = (long) dx * dx + (long) dy * dy;
                    if (dist > thresholdDist) continue;
                    int id = (int) w1;
                    if (found < targetK) {
                        int i = found++;
                        while (i > 0) {
                            int par = (i - 1) >>> 1;
                            long pd = rDist[par];
                            int pid = rId[par];
                            if (pd > dist || (pd == dist && pid > id)) break;
                            rDist[i] = pd;
                            rId[i] = pid;
                            i = par;
                        }
                        rDist[i] = dist;
                        rId[i] = id;
                        if (found == targetK) {
                            thresholdDist = rDist[0];
                            thresholdId = rId[0];
                        }
                    } else if (dist < thresholdDist || id < thresholdId) {
                        int i = 0;
                        while (i < halfK) {
                            int c = (i << 1) + 1;
                            long cd = rDist[c];
                            int cid = rId[c];
                            int r = c + 1;
                            if (r < targetK) {
                                long rd = rDist[r];
                                int rid = rId[r];
                                if (rd > cd || (rd == cd && rid > cid)) {
                                    c = r;
                                    cd = rd;
                                    cid = rid;
                                }
                            }
                            if (dist > cd || (dist == cd && id > cid)) break;
                            rDist[i] = cd;
                            rId[i] = cid;
                            i = c;
                        }
                        rDist[i] = dist;
                        rId[i] = id;
                        thresholdDist = rDist[0];
                        thresholdId = rId[0];
                    }
                }
            } else if (curLevel == 1) {
                for (int p = base; p < end; p += 2) {
                    long w0 = pool[p];
                    long w1 = pool[p + 1];
                    int dx = Math.max(0, Math.max((int) (w0 & COORD_MASK) - px, (int) (w0 >>> 42) - invPx));
                    int dy = Math.max(0, Math.max((int) ((w0 >>> 21) & COORD_MASK) - py, py - (int) (w1 >>> 42)));
                    long dist = (long) dx * dx + (long) dy * dy;
                    if (dist > thresholdDist) continue;
                    int leaf = (int) w1;
                    if (dist == 0L) {
                        int lb = (leaf << NODE_LONGS_SHIFT) + POOL_PAD;
                        int le = lb + (counts[leaf] << 1);
                        for (int lp = lb; lp < le; lp += 2) {
                            long lw0 = pool[lp];
                            long lw1 = pool[lp + 1];
                            int ldx = Math.max(0, Math.max((int) (lw0 & COORD_MASK) - px, (int) (lw0 >>> 42) - invPx));
                            int ldy = Math.max(0, Math.max((int) ((lw0 >>> 21) & COORD_MASK) - py, py - (int) (lw1 >>> 42)));
                            long ldist = (long) ldx * ldx + (long) ldy * ldy;
                            if (ldist > thresholdDist) continue;
                            int id = (int) lw1;
                            if (found < targetK) {
                                int i = found++;
                                while (i > 0) {
                                    int par = (i - 1) >>> 1;
                                    long pd = rDist[par];
                                    int pid = rId[par];
                                    if (pd > ldist || (pd == ldist && pid > id)) break;
                                    rDist[i] = pd;
                                    rId[i] = pid;
                                    i = par;
                                }
                                rDist[i] = ldist;
                                rId[i] = id;
                                if (found == targetK) {
                                    thresholdDist = rDist[0];
                                    thresholdId = rId[0];
                                }
                            } else if (ldist < thresholdDist || id < thresholdId) {
                                int i = 0;
                                while (i < halfK) {
                                    int c = (i << 1) + 1;
                                    long cd = rDist[c];
                                    int cid = rId[c];
                                    int r = c + 1;
                                    if (r < targetK) {
                                        long rd = rDist[r];
                                        int rid = rId[r];
                                        if (rd > cd || (rd == cd && rid > cid)) {
                                            c = r;
                                            cd = rd;
                                            cid = rid;
                                        }
                                    }
                                    if (ldist > cd || (ldist == cd && id > cid)) break;
                                    rDist[i] = cd;
                                    rId[i] = cid;
                                    i = c;
                                }
                                rDist[i] = ldist;
                                rId[i] = id;
                                thresholdDist = rDist[0];
                                thresholdId = rId[0];
                            }
                        }
                    } else if (dist < nextChildDist) {
                        if (nextChild >= 0 && nextChildDist <= thresholdDist) {
                            pqSize = pqPush(nextChildDist, nextChild, pqSize);
                        }
                        nextChildDist = dist;
                        nextChild = leaf;
                    } else {
                        pqSize = pqPush(dist, leaf, pqSize);
                    }
                }
            } else {
                int childLevelShift = (curLevel - 1) << 24;
                for (int p = base; p < end; p += 2) {
                    long w0 = pool[p];
                    long w1 = pool[p + 1];
                    int dx = Math.max(0, Math.max((int) (w0 & COORD_MASK) - px, (int) (w0 >>> 42) - invPx));
                    int dy = Math.max(0, Math.max((int) ((w0 >>> 21) & COORD_MASK) - py, py - (int) (w1 >>> 42)));
                    long dist = (long) dx * dx + (long) dy * dy;
                    if (dist > thresholdDist) continue;
                    int childTagged = ((int) w1) | childLevelShift;
                    if (dist < nextChildDist) {
                        if (nextChild >= 0) {
                            pqSize = pqPush(nextChildDist, nextChild, pqSize);
                        }
                        nextChildDist = dist;
                        nextChild = childTagged;
                    } else {
                        pqSize = pqPush(dist, childTagged, pqSize);
                    }
                }
            }

            if (nextChild >= 0 && nextChildDist <= thresholdDist) {
                if (pqSize == 0 || nextChildDist <= this.pqDist[0]) {
                    curLevel = nextChild >>> 24;
                    curNode = nextChild & 0x00FFFFFF;
                    continue;
                }
                pqSize = pqPush(nextChildDist, nextChild, pqSize);
            }

            final long[] pqD = this.pqDist;
            if (pqSize == 0 || pqD[0] > thresholdDist) break;

            final int[] pqN = this.pqNode;
            int top = pqN[0];
            curLevel = top >>> 24;
            curNode = top & 0x00FFFFFF;

            int last = --pqSize;
            if (last > 0) {
                long moveD = pqD[last];
                int moveN = pqN[last];
                int i = 0;
                while (true) {
                    int c = (i << 2) + 1;
                    if (c >= last) break;
                    int best = c;
                    long minD = pqD[c];
                    int cEnd = c + 4;
                    if (cEnd > last) cEnd = last;
                    for (int j = c + 1; j < cEnd; j++) {
                        long d = pqD[j];
                        if (d < minD) {
                            minD = d;
                            best = j;
                        }
                    }
                    if (moveD <= minD) break;
                    pqD[i] = minD;
                    pqN[i] = pqN[best];
                    i = best;
                }
                pqD[i] = moveD;
                pqN[i] = moveN;
            }
        }

        extractTopK(rDist, rId, found, outIds);
        return found;
    }

    private static void extractTopK(long[] rDist, int[] rId, int found, int[] outIds) {
        for (int pos = found - 1; pos >= 0; pos--) {
            outIds[pos] = rId[0];
            if (pos > 0) {
                long md = rDist[pos];
                int mid = rId[pos];
                int i = 0;
                int half = pos >>> 1;
                while (i < half) {
                    int c = (i << 1) + 1;
                    long cd = rDist[c];
                    int cid = rId[c];
                    int r = c + 1;
                    if (r < pos) {
                        long rd = rDist[r];
                        int rid = rId[r];
                        if (rd > cd || (rd == cd && rid > cid)) {
                            c = r;
                            cd = rd;
                            cid = rid;
                        }
                    }
                    if (md > cd || (md == cd && mid > cid)) break;
                    rDist[i] = cd;
                    rId[i] = cid;
                    i = c;
                }
                rDist[i] = md;
                rId[i] = mid;
            }
        }
    }
}
