import java.util.Arrays;

public final class RBTree {
    // Node layout in flat long[] arena:
    //   nodes[u]     = key (signed 64-bit)
    //   nodes[u + 1] = links:
    //                    bit 63     : color (1 = RED, 0 = BLACK)
    //                    bits 32..62: left child index (0 = NIL)
    //                    bit 31     : always 0
    //                    bits 0..30 : right child index (0 = NIL)
    //   nodes[u + 2] = value (signed 64-bit)
    //
    // Cache-line alignment on 64-bit HotSpot (16-byte array header, 128-byte cache lines):
    //   nodes[14] begins at byte offset 128 (start of cache line 1).
    //   Each 128-byte cache line (16 longs) packs 5 nodes (15 longs) + 1 padding long,
    //   so no node ever straddles a 128-byte cache line boundary in humongous arrays.
    //   nodes[0..2] is the immutable NIL sentinel (all zeros: BLACK, left=0, right=0).

    private static final long COLOR_BIT          = Long.MIN_VALUE;            // 0x8000_0000_0000_0000L
    private static final long LEFT_CLEAR         = 0x8000_0000_FFFF_FFFFL;    // preserves color & right
    private static final long RIGHT_CLEAR        = 0xFFFF_FFFF_0000_0000L;    // preserves color & left
    private static final long LEFT_MASK_NO_COLOR = 0x7FFF_FFFF_0000_0000L;    // preserves left only (BLACK)
    private static final int  MASK31             = 0x7FFF_FFFF;
    private static final int  FIRST_SLOT         = 14;
    private static final int  INITIAL_CAPACITY   = 64;

    private long[] nodes;
    private int root;
    private int size;
    private int nextSlot;
    private int freeHead;

    // Reusable ancestor stack for insert, remove, and range (max RB height <= 60 for < 2^30 nodes).
    // Bit 31 encodes traversal direction (0 = went left, 1 = went right).
    private final int[] path;

    public RBTree() {
        this.nodes = new long[INITIAL_CAPACITY];
        this.root = 0;
        this.size = 0;
        this.nextSlot = FIRST_SLOT;
        this.freeHead = 0;
        this.path = new int[64];
    }

    private long[] grow() {
        long[] old = this.nodes;
        int oldLen = old.length;
        int newLen = (oldLen >= (Integer.MAX_VALUE >>> 1)) ? (Integer.MAX_VALUE - 8) : (oldLen << 1);
        long[] next = Arrays.copyOf(old, newLen);
        this.nodes = next;
        return next;
    }

    public long get(long key, long missing) {
        final long[] a = this.nodes;
        int u = this.root;
        while (u > 0) {
            long links = a[u + 1];
            long k = a[u];
            if (key == k) {
                return a[u + 2];
            }
            int l = ((int) (links >>> 32)) & MASK31;
            int r = (int) links;
            u = (key < k) ? l : r;
        }
        return missing;
    }

    public boolean insert(long key, long value) {
        long[] a = this.nodes;
        int u = this.root;
        if (u == 0) {
            int x = FIRST_SLOT;
            this.nextSlot = FIRST_SLOT + 3;
            a[x] = key;
            a[x + 1] = 0L; // BLACK leaf
            a[x + 2] = value;
            this.root = x;
            this.size = 1;
            return true;
        }

        final int[] path = this.path;
        int sp = 0;
        while (u > 0) {
            long links = a[u + 1];
            long k = a[u];
            if (key == k) {
                a[u + 2] = value;
                return false;
            }
            int l = ((int) (links >>> 32)) & MASK31;
            int r = (int) links;
            boolean goLeft = key < k;
            path[sp++] = goLeft ? u : (u | Integer.MIN_VALUE);
            u = goLeft ? l : r;
        }

        // Allocate node (reuse free list if available, else bump aligned slot)
        int x = this.freeHead;
        if (x != 0) {
            this.freeHead = (int) a[x];
        } else {
            x = this.nextSlot;
            if (x + 3 > a.length) {
                a = grow();
            }
            this.nextSlot = x + (((x & 15) == 10) ? 4 : 3);
        }

        a[x] = key;
        a[x + 1] = COLOR_BIT; // RED leaf
        a[x + 2] = value;
        this.size++;

        int pEntry = path[--sp];
        int p = pEntry & MASK31;
        long pLinks = a[p + 1];
        if (pEntry >= 0) {
            a[p + 1] = (pLinks & LEFT_CLEAR) | ((long) x << 32);
        } else {
            a[p + 1] = (pLinks & RIGHT_CLEAR) | x;
        }

        if (pLinks < 0) {
            // Parent is RED -> fix red-red violation
            insertFixup(a, x, pEntry, sp);
        }
        return true;
    }

    private void insertFixup(long[] a, int x, int pEntry, int sp) {
        final int[] path = this.path;
        int p = pEntry & MASK31;

        while (true) {
            int gEntry = path[--sp];
            int g = gEntry & MASK31;
            long gLinks = a[g + 1];

            if (gEntry >= 0) {
                // p is g's LEFT child; uncle is g's RIGHT child
                int uncle = (int) gLinks;
                long uLinks = a[uncle + 1];
                if (uLinks < 0) {
                    // Case 1: uncle is RED
                    a[p + 1] &= Long.MAX_VALUE;
                    a[uncle + 1] = uLinks & Long.MAX_VALUE;
                    if (sp == 0) {
                        return; // g is root -> stays BLACK
                    }
                    a[g + 1] = gLinks | COLOR_BIT;
                    x = g;
                    pEntry = path[--sp];
                    p = pEntry & MASK31;
                    if (a[p + 1] >= 0) {
                        return;
                    }
                } else {
                    // Case 2/3: uncle is BLACK -> rotate and finish
                    long pLinks = a[p + 1];
                    int top;
                    if (pEntry < 0) {
                        // LR double rotation
                        int pLeft = ((int) (pLinks >>> 32)) & MASK31;
                        long xLinks = a[x + 1];
                        int xLeft = ((int) (xLinks >>> 32)) & MASK31;
                        int xRight = (int) xLinks;
                        a[p + 1] = COLOR_BIT | ((long) pLeft << 32) | xLeft;
                        a[g + 1] = COLOR_BIT | ((long) xRight << 32) | uncle;
                        a[x + 1] = ((long) p << 32) | g; // BLACK
                        top = x;
                    } else {
                        // LL single right rotation
                        int pRight = (int) pLinks;
                        a[g + 1] = COLOR_BIT | ((long) pRight << 32) | uncle;
                        a[p + 1] = ((long) x << 32) | g; // BLACK
                        top = p;
                    }
                    if (sp == 0) {
                        this.root = top;
                    } else {
                        int gpEntry = path[sp - 1];
                        int gp = gpEntry & MASK31;
                        if (gpEntry >= 0) {
                            a[gp + 1] = (a[gp + 1] & LEFT_CLEAR) | ((long) top << 32);
                        } else {
                            a[gp + 1] = (a[gp + 1] & RIGHT_CLEAR) | top;
                        }
                    }
                    return;
                }
            } else {
                // p is g's RIGHT child; uncle is g's LEFT child
                int uncle = ((int) (gLinks >>> 32)) & MASK31;
                long uLinks = a[uncle + 1];
                if (uLinks < 0) {
                    // Case 1: uncle is RED
                    a[p + 1] &= Long.MAX_VALUE;
                    a[uncle + 1] = uLinks & Long.MAX_VALUE;
                    if (sp == 0) {
                        return; // g is root -> stays BLACK
                    }
                    a[g + 1] = gLinks | COLOR_BIT;
                    x = g;
                    pEntry = path[--sp];
                    p = pEntry & MASK31;
                    if (a[p + 1] >= 0) {
                        return;
                    }
                } else {
                    // Case 2/3: uncle is BLACK -> rotate and finish
                    long pLinks = a[p + 1];
                    int top;
                    if (pEntry >= 0) {
                        // RL double rotation
                        int pRight = (int) pLinks;
                        long xLinks = a[x + 1];
                        int xLeft = ((int) (xLinks >>> 32)) & MASK31;
                        int xRight = (int) xLinks;
                        a[g + 1] = COLOR_BIT | ((long) uncle << 32) | xLeft;
                        a[p + 1] = COLOR_BIT | ((long) xRight << 32) | pRight;
                        a[x + 1] = ((long) g << 32) | p; // BLACK
                        top = x;
                    } else {
                        // RR single left rotation
                        int pLeft = ((int) (pLinks >>> 32)) & MASK31;
                        a[g + 1] = COLOR_BIT | ((long) uncle << 32) | pLeft;
                        a[p + 1] = ((long) g << 32) | x; // BLACK
                        top = p;
                    }
                    if (sp == 0) {
                        this.root = top;
                    } else {
                        int gpEntry = path[sp - 1];
                        int gp = gpEntry & MASK31;
                        if (gpEntry >= 0) {
                            a[gp + 1] = (a[gp + 1] & LEFT_CLEAR) | ((long) top << 32);
                        } else {
                            a[gp + 1] = (a[gp + 1] & RIGHT_CLEAR) | top;
                        }
                    }
                    return;
                }
            }
        }
    }

    public boolean remove(long key) {
        final long[] a = this.nodes;
        int u = this.root;
        if (u == 0) {
            return false;
        }

        final int[] path = this.path;
        int sp = 0;
        long uLinks;
        while (true) {
            uLinks = a[u + 1];
            long k = a[u];
            if (key == k) {
                break;
            }
            int l = ((int) (uLinks >>> 32)) & MASK31;
            int r = (int) uLinks;
            boolean goLeft = key < k;
            path[sp++] = goLeft ? u : (u | Integer.MIN_VALUE);
            u = goLeft ? l : r;
            if (u == 0) {
                return false;
            }
        }

        if (--this.size == 0) {
            this.root = 0;
            this.freeHead = 0;
            this.nextSlot = FIRST_SLOT;
            return true;
        }

        int uLeft = ((int) (uLinks >>> 32)) & MASK31;
        int uRight = (int) uLinks;
        int del;
        int child;
        boolean delWasBlack;

        if (uLeft != 0 && uRight != 0) {
            // Find in-order successor (minimum of right subtree)
            path[sp++] = u | Integer.MIN_VALUE;
            int s = uRight;
            long sLinks = a[s + 1];
            int sLeft = ((int) (sLinks >>> 32)) & MASK31;
            while (sLeft != 0) {
                path[sp++] = s;
                s = sLeft;
                sLinks = a[s + 1];
                sLeft = ((int) (sLinks >>> 32)) & MASK31;
            }
            a[u] = a[s];
            a[u + 2] = a[s + 2];
            del = s;
            child = (int) sLinks;
            delWasBlack = sLinks >= 0;
        } else {
            del = u;
            child = (uLeft != 0) ? uLeft : uRight;
            delWasBlack = uLinks >= 0;
        }

        // Return unlinked node to free list
        a[del] = this.freeHead;
        this.freeHead = del;

        if (sp == 0) {
            this.root = child;
            a[child + 1] &= Long.MAX_VALUE;
            return true;
        }

        int pEntry = path[--sp];
        int p = pEntry & MASK31;
        if (pEntry >= 0) {
            a[p + 1] = (a[p + 1] & LEFT_CLEAR) | ((long) child << 32);
        } else {
            a[p + 1] = (a[p + 1] & RIGHT_CLEAR) | child;
        }

        if (!delWasBlack) {
            return true;
        }

        if (a[child + 1] < 0) {
            a[child + 1] &= Long.MAX_VALUE;
            return true;
        }

        removeFixup(a, pEntry, sp);
        return true;
    }

    private void removeFixup(long[] a, int pEntry, int sp) {
        final int[] path = this.path;
        int p = pEntry & MASK31;

        while (true) {
            long pLinks = a[p + 1];

            if (pEntry >= 0) {
                // Deficit on p's LEFT child; sibling w is p's RIGHT child
                int w = (int) pLinks;
                long wLinks = a[w + 1];

                if (wLinks < 0) {
                    // Case 1: w is RED -> rotate left at p, recolor, fall through
                    int wL = ((int) (wLinks >>> 32)) & MASK31;
                    pLinks = COLOR_BIT | (pLinks & RIGHT_CLEAR) | wL;
                    a[p + 1] = pLinks;
                    a[w + 1] = ((long) p << 32) | ((int) wLinks);
                    if (sp == 0) {
                        this.root = w;
                    } else {
                        int gpEntry = path[sp - 1];
                        int gp = gpEntry & MASK31;
                        if (gpEntry >= 0) {
                            a[gp + 1] = (a[gp + 1] & LEFT_CLEAR) | ((long) w << 32);
                        } else {
                            a[gp + 1] = (a[gp + 1] & RIGHT_CLEAR) | w;
                        }
                    }
                    path[sp++] = w;
                    w = wL;
                    wLinks = a[w + 1];
                }

                int wL = ((int) (wLinks >>> 32)) & MASK31;
                int wR = (int) wLinks;
                long wLLinks = a[wL + 1];
                long wRLinks = a[wR + 1];

                if (wLLinks >= 0 && wRLinks >= 0) {
                    // Case 2: both children of w are BLACK
                    a[w + 1] = wLinks | COLOR_BIT;
                    if (pLinks < 0) {
                        a[p + 1] = pLinks & Long.MAX_VALUE;
                        return;
                    }
                    if (sp == 0) {
                        return;
                    }
                    pEntry = path[--sp];
                    p = pEntry & MASK31;
                } else {
                    int top;
                    if (wRLinks >= 0) {
                        // Case 3 + 4 combined: wL is RED, wR is BLACK -> double rotation
                        int wLL = ((int) (wLLinks >>> 32)) & MASK31;
                        int wLR = (int) wLLinks;
                        a[p + 1] = (pLinks & LEFT_MASK_NO_COLOR) | wLL;
                        a[w + 1] = ((long) wLR << 32) | wR;
                        a[wL + 1] = (pLinks & COLOR_BIT) | ((long) p << 32) | w;
                        top = wL;
                    } else {
                        // Case 4: wR is RED -> single left rotation at p
                        a[p + 1] = (pLinks & LEFT_MASK_NO_COLOR) | wL;
                        a[wR + 1] = wRLinks & Long.MAX_VALUE;
                        a[w + 1] = (pLinks & COLOR_BIT) | ((long) p << 32) | wR;
                        top = w;
                    }
                    if (sp == 0) {
                        this.root = top;
                    } else {
                        int gpEntry = path[sp - 1];
                        int gp = gpEntry & MASK31;
                        if (gpEntry >= 0) {
                            a[gp + 1] = (a[gp + 1] & LEFT_CLEAR) | ((long) top << 32);
                        } else {
                            a[gp + 1] = (a[gp + 1] & RIGHT_CLEAR) | top;
                        }
                    }
                    return;
                }
            } else {
                // Deficit on p's RIGHT child; sibling w is p's LEFT child
                int w = ((int) (pLinks >>> 32)) & MASK31;
                long wLinks = a[w + 1];

                if (wLinks < 0) {
                    // Case 1: w is RED -> rotate right at p, recolor, fall through
                    int wR = (int) wLinks;
                    pLinks = COLOR_BIT | ((long) wR << 32) | ((int) pLinks);
                    a[p + 1] = pLinks;
                    a[w + 1] = (wLinks & LEFT_MASK_NO_COLOR) | p;
                    if (sp == 0) {
                        this.root = w;
                    } else {
                        int gpEntry = path[sp - 1];
                        int gp = gpEntry & MASK31;
                        if (gpEntry >= 0) {
                            a[gp + 1] = (a[gp + 1] & LEFT_CLEAR) | ((long) w << 32);
                        } else {
                            a[gp + 1] = (a[gp + 1] & RIGHT_CLEAR) | w;
                        }
                    }
                    path[sp++] = w | Integer.MIN_VALUE;
                    w = wR;
                    wLinks = a[w + 1];
                }

                int wL = ((int) (wLinks >>> 32)) & MASK31;
                int wR = (int) wLinks;
                long wLLinks = a[wL + 1];
                long wRLinks = a[wR + 1];

                if (wLLinks >= 0 && wRLinks >= 0) {
                    // Case 2: both children of w are BLACK
                    a[w + 1] = wLinks | COLOR_BIT;
                    if (pLinks < 0) {
                        a[p + 1] = pLinks & Long.MAX_VALUE;
                        return;
                    }
                    if (sp == 0) {
                        return;
                    }
                    pEntry = path[--sp];
                    p = pEntry & MASK31;
                } else {
                    int top;
                    if (wLLinks >= 0) {
                        // Case 3 + 4 combined: wR is RED, wL is BLACK -> double rotation
                        int wRL = ((int) (wRLinks >>> 32)) & MASK31;
                        int wRR = (int) wRLinks;
                        a[p + 1] = ((long) wRR << 32) | ((int) pLinks);
                        a[w + 1] = ((long) wL << 32) | wRL;
                        a[wR + 1] = (pLinks & COLOR_BIT) | ((long) w << 32) | p;
                        top = wR;
                    } else {
                        // Case 4: wL is RED -> single right rotation at p
                        a[p + 1] = ((long) wR << 32) | ((int) pLinks);
                        a[wL + 1] = wLLinks & Long.MAX_VALUE;
                        a[w + 1] = (pLinks & COLOR_BIT) | ((long) wL << 32) | p;
                        top = w;
                    }
                    if (sp == 0) {
                        this.root = top;
                    } else {
                        int gpEntry = path[sp - 1];
                        int gp = gpEntry & MASK31;
                        if (gpEntry >= 0) {
                            a[gp + 1] = (a[gp + 1] & LEFT_CLEAR) | ((long) top << 32);
                        } else {
                            a[gp + 1] = (a[gp + 1] & RIGHT_CLEAR) | top;
                        }
                    }
                    return;
                }
            }
        }
    }

    public int range(long lo, long hi, long[] outKeys, long[] outVals, int limit) {
        if (limit <= 0 || lo > hi) {
            return 0;
        }
        if (limit > outKeys.length || limit > outVals.length) {
            throw new IndexOutOfBoundsException();
        }
        int u = this.root;
        if (u == 0) {
            return 0;
        }

        final long[] a = this.nodes;
        final int[] st = this.path;
        int sp = 0;

        // Phase 1: branchless seek to smallest key >= lo
        while (u > 0) {
            long links = a[u + 1];
            long k = a[u];
            if (k == lo) {
                break;
            }
            int l = ((int) (links >>> 32)) & MASK31;
            int r = (int) links;
            st[sp] = u;
            boolean goLeft = k > lo;
            sp += goLeft ? 1 : 0;
            u = goLeft ? l : r;
        }

        if (u == 0) {
            if (sp == 0) {
                return 0;
            }
            u = st[--sp];
        }

        // Phase 2: in-order walk using RB leaf invariant on left-bottom nodes
        int count = 0;
        outer:
        while (true) {
            long val = a[u + 2];
            long links = a[u + 1];
            long k = a[u];
            if (k > hi) {
                return count;
            }
            outKeys[count] = k;
            outVals[count] = val;
            if (++count == limit) {
                return count;
            }

            int r = (int) links;
            if (r > 0) {
                while (true) {
                    long rLinks = a[r + 1];
                    int l = ((int) (rLinks >>> 32)) & MASK31;
                    if (l == 0) {
                        long rv = a[r + 2];
                        long rk = a[r];
                        if (rk > hi) {
                            return count;
                        }
                        outKeys[count] = rk;
                        outVals[count] = rv;
                        if (++count == limit) {
                            return count;
                        }

                        int rr = (int) rLinks;
                        if (rr > 0) {
                            // RB invariant: when left(r) == 0, any right child rr is a red leaf.
                            long rrv = a[rr + 2];
                            long rrk = a[rr];
                            if (rrk > hi) {
                                return count;
                            }
                            outKeys[count] = rrk;
                            outVals[count] = rrv;
                            if (++count == limit) {
                                return count;
                            }
                        }

                        if (sp == 0) {
                            return count;
                        }
                        u = st[--sp];
                        continue outer;
                    }
                    st[sp++] = r;
                    r = l;
                }
            } else {
                if (sp == 0) {
                    return count;
                }
                u = st[--sp];
            }
        }
    }

    public int size() {
        return this.size;
    }

    public int height() {
        return heightOf(this.nodes, this.root);
    }

    private static int heightOf(long[] a, int u) {
        if (u == 0) {
            return 0;
        }
        long links = a[u + 1];
        int l = ((int) (links >>> 32)) & MASK31;
        int r = (int) links;
        int lh = heightOf(a, l);
        int rh = heightOf(a, r);
        return (lh >= rh ? lh : rh) + 1;
    }
}
