// Red-black tree (classic, bottom-up rebalancing with an explicit path stack).
//
// Node layout (32 bytes, 32-byte aligned so a node never straddles a cache
// line):  key | value | left-link|colour-bit | right-link
// The colour of a node is kept in the low bit of its own left link
// (1 = red). Missing children point at a per-tree black sentinel node, which
// lets searches terminate by planting the search key in the sentinel.
#pragma once

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <new>
#include <optional>
#include <vector>

class RBTree {
    struct alignas(32) Node {
        std::int64_t key;
        std::int64_t val;
        std::uintptr_t c[2];  // c[0] carries the colour bit
    };

    static constexpr int kMaxDepth = 160;
    static constexpr std::size_t kMaxSlab = std::size_t(1) << 20;  // nodes

    Node* root_;
    std::size_t count_ = 0;
    mutable Node nil_;

    // node pool
    Node* free_ = nullptr;
    Node* bump_ = nullptr;
    Node* end_ = nullptr;
    std::size_t capacity_ = 0;
    std::vector<void*> slabs_;

    // ---------------------------------------------------------------- helpers
    static inline Node* ch(const Node* n, int d) {
        return reinterpret_cast<Node*>(n->c[d] & ~std::uintptr_t(1));
    }
    static inline void setch(Node* n, int d, Node* p) {
        n->c[d] = reinterpret_cast<std::uintptr_t>(p) | (n->c[d] & 1);
    }
    static inline bool red(const Node* n) { return n->c[0] & 1; }
    static inline void set_red(Node* n) { n->c[0] |= 1; }
    static inline void set_black(Node* n) { n->c[0] &= ~std::uintptr_t(1); }

    // Rotate so that n's child in direction !d becomes the subtree root.
    static inline Node* rotate(Node* n, int d) {
        Node* c = ch(n, !d);
        setch(n, !d, ch(c, d));
        setch(c, d, n);
        return c;
    }

    inline void link(Node** stk, const std::uint8_t* dirs, int j, Node* t) {
        if (j < 0)
            root_ = t;
        else
            setch(stk[j], dirs[j], t);
    }

    __attribute__((noinline)) void grow() {
        std::size_t sz = capacity_ == 0 ? 512 : std::min(capacity_, kMaxSlab);
        void* p = ::operator new(sz * sizeof(Node), std::align_val_t(128));
        slabs_.push_back(p);
        bump_ = static_cast<Node*>(p);
        end_ = bump_ + sz;
        capacity_ += sz;
    }

    inline Node* alloc() {
        if (free_) {
            Node* n = free_;
            free_ = reinterpret_cast<Node*>(n->c[1]);
            return n;
        }
        if (__builtin_expect(bump_ == end_, 0)) grow();
        return bump_++;
    }

    inline void release(Node* n) {
        n->c[1] = reinterpret_cast<std::uintptr_t>(free_);
        free_ = n;
    }

    std::size_t height_of(const Node* n) const {
        if (n == &nil_) return 0;
        std::size_t l = height_of(ch(n, 0)), r = height_of(ch(n, 1));
        return 1 + (l > r ? l : r);
    }

public:
    RBTree() {
        nil_.key = 0;
        nil_.val = 0;
        nil_.c[0] = reinterpret_cast<std::uintptr_t>(&nil_);  // black
        nil_.c[1] = reinterpret_cast<std::uintptr_t>(&nil_);
        root_ = &nil_;
    }

    ~RBTree() {
        for (void* p : slabs_) ::operator delete(p, std::align_val_t(128));
    }

    RBTree(const RBTree&) = delete;
    RBTree& operator=(const RBTree&) = delete;

    bool insert(std::int64_t key, std::int64_t value) {
        Node* stk[kMaxDepth];
        std::uint8_t dirs[kMaxDepth];
        Node* const nil = &nil_;
        nil->key = key;
        Node* n = root_;
        int top = 0;
        while (n->key != key) {
            int d = key > n->key;
            stk[top] = n;
            dirs[top] = (std::uint8_t)d;
            ++top;
            n = ch(n, d);
        }
        if (n != nil) {
            n->val = value;
            return false;
        }

        Node* x = alloc();
        x->key = key;
        x->val = value;
        x->c[0] = reinterpret_cast<std::uintptr_t>(nil) | 1;  // red
        x->c[1] = reinterpret_cast<std::uintptr_t>(nil);
        ++count_;
        if (top == 0) {
            set_black(x);
            root_ = x;
            return true;
        }
        setch(stk[top - 1], dirs[top - 1], x);

        int i = top - 1;  // stack index of x's parent
        for (;;) {
            Node* p = stk[i];
            if (!red(p)) break;
            // p is red, hence not the root: i >= 1
            Node* g = stk[i - 1];
            int pd = dirs[i - 1];
            Node* u = ch(g, !pd);
            if (red(u)) {
                set_black(p);
                set_black(u);
                set_red(g);
                x = g;
                i -= 2;
                if (i < 0) {
                    set_black(g);  // g is the root
                    break;
                }
                continue;
            }
            if (dirs[i] != pd) {
                setch(g, pd, rotate(p, pd));
                p = x;
            }
            set_black(p);
            set_red(g);
            Node* t = rotate(g, !pd);
            link(stk, dirs, i - 2, t);
            break;
        }
        return true;
    }

    std::optional<std::int64_t> get(std::int64_t key) const {
        const Node* const nil = &nil_;
        nil_.key = key;
        const Node* n = root_;
        while (n->key != key) n = ch(n, key > n->key);
        if (n == nil) return std::nullopt;
        return n->val;
    }

    bool remove(std::int64_t key) {
        Node* stk[kMaxDepth];
        std::uint8_t dirs[kMaxDepth];
        Node* const nil = &nil_;
        nil->key = key;
        Node* n = root_;
        int top = 0;
        while (n->key != key) {
            int d = key > n->key;
            stk[top] = n;
            dirs[top] = (std::uint8_t)d;
            ++top;
            n = ch(n, d);
        }
        if (n == nil) return false;

        Node* y = n;
        Node* x;
        Node* l = ch(n, 0);
        Node* r = ch(n, 1);
        if (l != nil && r != nil) {
            stk[top] = n;
            dirs[top] = 1;
            ++top;
            y = r;
            for (Node* yl; (yl = ch(y, 0)) != nil; y = yl) {
                stk[top] = y;
                dirs[top] = 0;
                ++top;
            }
            n->key = y->key;
            n->val = y->val;
            x = ch(y, 1);
        } else {
            x = l != nil ? l : r;
        }
        link(stk, dirs, top - 1, x);
        bool yred = red(y);
        release(y);
        --count_;
        if (yred) return true;
        if (red(x)) {
            set_black(x);
            return true;
        }

        // x (possibly nil) is doubly black at stk[i].c[dirs[i]]
        int i = top - 1;
        while (i >= 0) {
            Node* p = stk[i];
            int d = dirs[i];
            Node* s = ch(p, !d);
            if (red(s)) {
                set_black(s);
                set_red(p);
                rotate(p, d);
                link(stk, dirs, i - 1, s);
                stk[i] = s;
                dirs[i] = (std::uint8_t)d;
                ++i;
                stk[i] = p;
                dirs[i] = (std::uint8_t)d;
                s = ch(p, !d);
            }
            Node* sn = ch(s, d);
            Node* sf = ch(s, !d);
            if (!red(sf)) {
                if (!red(sn)) {
                    set_red(s);
                    if (red(p)) {
                        set_black(p);
                        break;
                    }
                    --i;
                    continue;
                }
                set_black(sn);
                set_red(s);
                setch(p, !d, rotate(s, !d));
                sf = s;
                s = sn;
            }
            s->c[0] = (s->c[0] & ~std::uintptr_t(1)) | (p->c[0] & 1);
            set_black(p);
            set_black(sf);
            rotate(p, d);
            link(stk, dirs, i - 1, s);
            break;
        }
        return true;
    }

    std::size_t range(std::int64_t lo, std::int64_t hi, std::int64_t* out_keys,
                      std::int64_t* out_vals, std::size_t limit) const {
        if (lo > hi || limit == 0) return 0;
        const Node* stk[kMaxDepth];
        const Node* const nil = &nil_;
        int top = 0;
        const Node* n = root_;
        while (n != nil) {
            int d = n->key < lo;
            stk[top] = n;
            top += !d;
            n = ch(n, d);
        }
        std::size_t cnt = 0;
        while (top > 0) {
            n = stk[--top];
            std::int64_t k = n->key;
            if (k > hi) break;
            out_keys[cnt] = k;
            out_vals[cnt] = n->val;
            if (++cnt == limit) break;
            n = ch(n, 1);
            while (n != nil) {
                stk[top++] = n;
                n = ch(n, 0);
            }
        }
        return cnt;
    }

    std::size_t len() const { return count_; }

    std::size_t height() const { return height_of(root_); }
};
