// Classic B-tree (CLRS ch. 18), minimum degree t = 16.
#pragma once

#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <new>
#include <optional>
#include <vector>

class BTree {
    using i64 = std::int64_t;
    static constexpr int T = 16;
    static constexpr int MAXK = 2 * T - 1;  // 31
    static constexpr int MINK = T - 1;      // 15
    static constexpr i64 KMAX = std::numeric_limits<i64>::max();
    static constexpr int MAXH = 64;

    // keys[0..n) are live; keys[n..32) are always KMAX (padding / sentinel),
    // so a branch-free count of "keys < k" over all 32 slots equals the
    // lower-bound index within the live keys.
    struct alignas(128) Leaf {
        i64 keys[MAXK + 1];  // 256 bytes: two cache lines
        i64 vals[MAXK];
        std::int32_t n;
    };
    struct alignas(128) Inner : Leaf {
        Leaf* c[MAXK + 1];
    };
    static_assert(sizeof(Leaf) == 512);
    static_assert(sizeof(Inner) == 768);

    // Slab pool with a free list for one node size.
    struct Pool {
        void* freelist = nullptr;
        char* cur = nullptr;
        char* end = nullptr;
        std::size_t nextCount = 32;
        std::vector<void*> slabs;
        std::size_t sz;
        explicit Pool(std::size_t s) : sz(s) {}
        ~Pool() {
            for (void* p : slabs) ::operator delete(p, std::align_val_t(128));
        }
        inline void* alloc() {
            if (freelist) {
                void* p = freelist;
                freelist = *static_cast<void**>(p);
                return p;
            }
            if (__builtin_expect(cur == end, 0)) grow();
            void* p = cur;
            cur += sz;
            return p;
        }
        inline void release(void* p) {
            *static_cast<void**>(p) = freelist;
            freelist = p;
        }
        __attribute__((noinline)) void grow() {
            std::size_t bytes = nextCount * sz;
            void* p = ::operator new(bytes, std::align_val_t(128));
            slabs.push_back(p);
            cur = static_cast<char*>(p);
            end = cur + bytes;
            if (nextCount < 8192) nextCount *= 2;
        }
    };

    Leaf* root_ = nullptr;
    std::size_t count_ = 0;
    int height_ = 0;
    Pool leafPool_{sizeof(Leaf)};
    Pool innerPool_{sizeof(Inner)};

    static inline void fillMax(i64* p, int cnt) {
        for (int i = 0; i < cnt; i++) p[i] = KMAX;
    }
    inline Leaf* newLeaf() {
        Leaf* x = static_cast<Leaf*>(leafPool_.alloc());
        fillMax(x->keys, MAXK + 1);
        x->n = 0;
        return x;
    }
    inline Inner* newInner() {
        Inner* x = static_cast<Inner*>(innerPool_.alloc());
        fillMax(x->keys, MAXK + 1);
        x->n = 0;
        return x;
    }
    static inline Inner* in(Leaf* x) { return static_cast<Inner*>(x); }
    static inline const Inner* in(const Leaf* x) { return static_cast<const Inner*>(x); }

    // Number of live keys strictly less than k.
    static inline unsigned lowerBound(const i64* keys, i64 k) {
        i64 c = 0;
#pragma clang loop vectorize(enable) unroll(full)
        for (int i = 0; i < MAXK + 1; i++) c += (keys[i] < k);
        return (unsigned)c;
    }
    // Number of live keys <= k (bounded by n).
    static inline unsigned upperBound(const i64* keys, int n, i64 k) {
        i64 c = 0;
#pragma clang loop vectorize(enable) unroll(full)
        for (int i = 0; i < MAXK + 1; i++) c += (keys[i] <= k);
        return c > n ? (unsigned)n : (unsigned)c;
    }

    // Split full node x (31 keys) while inserting (K,V,R) at position i.
    // x keeps 16 keys, the new right node gets 15; the median is returned
    // through K/V and the new node through R.
    template <bool INNER>
    inline void splitInsert(Leaf* x, int i, i64& K, i64& V, Leaf*& R) {
        Leaf* y = INNER ? static_cast<Leaf*>(newInner()) : newLeaf();
        i64 mK, mV;
        if (i <= 15) {
            std::memcpy(y->keys, x->keys + 16, 15 * sizeof(i64));
            std::memcpy(y->vals, x->vals + 16, 15 * sizeof(i64));
            mK = x->keys[15];
            mV = x->vals[15];
            std::memmove(x->keys + i + 1, x->keys + i, (15 - i) * sizeof(i64));
            std::memmove(x->vals + i + 1, x->vals + i, (15 - i) * sizeof(i64));
            x->keys[i] = K;
            x->vals[i] = V;
            if constexpr (INNER) {
                Leaf** xc = in(x)->c;
                std::memcpy(in(y)->c, xc + 16, 16 * sizeof(Leaf*));
                std::memmove(xc + i + 2, xc + i + 1, (15 - i) * sizeof(Leaf*));
                xc[i + 1] = R;
            }
        } else if (i == 16) {
            std::memcpy(y->keys, x->keys + 16, 15 * sizeof(i64));
            std::memcpy(y->vals, x->vals + 16, 15 * sizeof(i64));
            mK = K;
            mV = V;
            if constexpr (INNER) {
                Leaf** xc = in(x)->c;
                Leaf** yc = in(y)->c;
                yc[0] = R;
                std::memcpy(yc + 1, xc + 17, 15 * sizeof(Leaf*));
            }
        } else {
            mK = x->keys[16];
            mV = x->vals[16];
            int a = i - 17;
            std::memcpy(y->keys, x->keys + 17, a * sizeof(i64));
            std::memcpy(y->vals, x->vals + 17, a * sizeof(i64));
            y->keys[a] = K;
            y->vals[a] = V;
            std::memcpy(y->keys + a + 1, x->keys + i, (31 - i) * sizeof(i64));
            std::memcpy(y->vals + a + 1, x->vals + i, (31 - i) * sizeof(i64));
            if constexpr (INNER) {
                Leaf** xc = in(x)->c;
                Leaf** yc = in(y)->c;
                std::memcpy(yc, xc + 17, (i - 16) * sizeof(Leaf*));
                yc[i - 16] = R;
                std::memcpy(yc + i - 15, xc + i + 1, (31 - i) * sizeof(Leaf*));
            }
        }
        fillMax(x->keys + 16, 15);
        x->n = 16;
        y->n = 15;
        K = mK;
        V = mV;
        R = y;
    }

    // Fix children j and j+1 of p (one of them has underflowed).
    // Returns true if they were merged (p lost a key).
    template <bool INNER>
    inline bool rebalance(Inner* p, int j) {
        Leaf* L = p->c[j];
        Leaf* R = p->c[j + 1];
        int nL = L->n, nR = R->n;
        if (nL + nR + 1 <= MAXK) {
            // merge R and separator into L
            L->keys[nL] = p->keys[j];
            L->vals[nL] = p->vals[j];
            std::memcpy(L->keys + nL + 1, R->keys, nR * sizeof(i64));
            std::memcpy(L->vals + nL + 1, R->vals, nR * sizeof(i64));
            if constexpr (INNER)
                std::memcpy(in(L)->c + nL + 1, in(R)->c, (nR + 1) * sizeof(Leaf*));
            L->n = nL + nR + 1;
            int pn = p->n;
            std::memmove(p->keys + j, p->keys + j + 1, (pn - j - 1) * sizeof(i64));
            std::memmove(p->vals + j, p->vals + j + 1, (pn - j - 1) * sizeof(i64));
            std::memmove(p->c + j + 1, p->c + j + 2, (pn - j - 1) * sizeof(Leaf*));
            pn--;
            p->keys[pn] = KMAX;
            p->n = pn;
            if constexpr (INNER)
                innerPool_.release(R);
            else
                leafPool_.release(R);
            return true;
        }
        int tot = nL + nR;
        int nL2 = tot / 2;
        int nR2 = tot - nL2;
        if (nL2 > nL) {
            // move m entries from R to L
            int m = nL2 - nL;
            L->keys[nL] = p->keys[j];
            L->vals[nL] = p->vals[j];
            std::memcpy(L->keys + nL + 1, R->keys, (m - 1) * sizeof(i64));
            std::memcpy(L->vals + nL + 1, R->vals, (m - 1) * sizeof(i64));
            p->keys[j] = R->keys[m - 1];
            p->vals[j] = R->vals[m - 1];
            std::memmove(R->keys, R->keys + m, nR2 * sizeof(i64));
            std::memmove(R->vals, R->vals + m, nR2 * sizeof(i64));
            fillMax(R->keys + nR2, m);
            if constexpr (INNER) {
                Leaf** lc = in(L)->c;
                Leaf** rc = in(R)->c;
                std::memcpy(lc + nL + 1, rc, m * sizeof(Leaf*));
                std::memmove(rc, rc + m, (nR2 + 1) * sizeof(Leaf*));
            }
        } else {
            // move m entries from L to R
            int m = nL - nL2;
            std::memmove(R->keys + m, R->keys, nR * sizeof(i64));
            std::memmove(R->vals + m, R->vals, nR * sizeof(i64));
            R->keys[m - 1] = p->keys[j];
            R->vals[m - 1] = p->vals[j];
            std::memcpy(R->keys, L->keys + nL2 + 1, (m - 1) * sizeof(i64));
            std::memcpy(R->vals, L->vals + nL2 + 1, (m - 1) * sizeof(i64));
            p->keys[j] = L->keys[nL2];
            p->vals[j] = L->vals[nL2];
            fillMax(L->keys + nL2, m);
            if constexpr (INNER) {
                Leaf** lc = in(L)->c;
                Leaf** rc = in(R)->c;
                std::memmove(rc + m, rc, (nR + 1) * sizeof(Leaf*));
                std::memcpy(rc, lc + nL2 + 1, m * sizeof(Leaf*));
            }
        }
        L->n = nL2;
        R->n = nR2;
        return false;
    }

    // Returns true when the walk must stop (key > hi seen or limit reached).
    bool rangeRec(const Leaf* x, int lvl, bool bounded, i64 lo, i64 hi, std::int64_t* ok,
                  std::int64_t* ov, std::size_t& cnt, std::size_t limit) const {
        int n = x->n;
        int j = bounded ? (int)lowerBound(x->keys, lo) : 0;
        if (lvl == 1) {
            int e = (int)upperBound(x->keys, n, hi);
            if (e > j) {
                std::size_t m = (std::size_t)(e - j);
                bool lim = false;
                if (m >= limit - cnt) {
                    m = limit - cnt;
                    lim = true;
                }
                std::memcpy(ok + cnt, x->keys + j, m * sizeof(i64));
                std::memcpy(ov + cnt, x->vals + j, m * sizeof(i64));
                cnt += m;
                if (lim) return true;
            }
            return e < n;
        }
        const Inner* xi = in(x);
        for (;; j++) {
            if (rangeRec(xi->c[j], lvl - 1, bounded, lo, hi, ok, ov, cnt, limit)) return true;
            bounded = false;
            if (j >= n) return false;
            i64 k = x->keys[j];
            if (k > hi) return true;
            ok[cnt] = k;
            ov[cnt] = x->vals[j];
            if (++cnt == limit) return true;
        }
    }

public:
    BTree() = default;
    ~BTree() = default;
    BTree(const BTree&) = delete;
    BTree& operator=(const BTree&) = delete;

    std::optional<std::int64_t> get(std::int64_t key) const {
        const Leaf* x = root_;
        if (!x) return std::nullopt;
        int h = height_;
        for (;;) {
            unsigned i = lowerBound(x->keys, key);
            if (x->keys[i] == key && (key != KMAX || (int)i < x->n)) return x->vals[i];
            if (--h == 0) return std::nullopt;
            x = in(x)->c[i];
            __builtin_prefetch(reinterpret_cast<const char*>(x) + 128);
        }
    }

    bool insert(std::int64_t key, std::int64_t value) {
        if (!root_) {
            Leaf* r = newLeaf();
            r->keys[0] = key;
            r->vals[0] = value;
            r->n = 1;
            root_ = r;
            height_ = 1;
            count_ = 1;
            return true;
        }
        Leaf* path[MAXH];
        int idx[MAXH];
        Leaf* x = root_;
        const int H = height_;
        int d = 0;
        for (;;) {
            unsigned i = lowerBound(x->keys, key);
            if ((int)i < x->n && x->keys[i] == key) {
                x->vals[i] = value;
                return false;
            }
            path[d] = x;
            idx[d] = (int)i;
            if (d == H - 1) break;
            x = in(x)->c[i];
            __builtin_prefetch(reinterpret_cast<const char*>(x) + 128);
            d++;
        }
        count_++;
        i64 K = key, V = value;
        Leaf* R = nullptr;
        // leaf level
        {
            int i = idx[d];
            int n = x->n;
            if (n < MAXK) {
                std::memmove(x->keys + i + 1, x->keys + i, (n - i) * sizeof(i64));
                std::memmove(x->vals + i + 1, x->vals + i, (n - i) * sizeof(i64));
                x->keys[i] = K;
                x->vals[i] = V;
                x->n = n + 1;
                return true;
            }
            splitInsert<false>(x, i, K, V, R);
        }
        while (d > 0) {
            d--;
            x = path[d];
            int i = idx[d];
            int n = x->n;
            if (n < MAXK) {
                std::memmove(x->keys + i + 1, x->keys + i, (n - i) * sizeof(i64));
                std::memmove(x->vals + i + 1, x->vals + i, (n - i) * sizeof(i64));
                Leaf** c = in(x)->c;
                std::memmove(c + i + 2, c + i + 1, (n - i) * sizeof(Leaf*));
                x->keys[i] = K;
                x->vals[i] = V;
                c[i + 1] = R;
                x->n = n + 1;
                return true;
            }
            splitInsert<true>(x, i, K, V, R);
        }
        Inner* r = newInner();
        r->keys[0] = K;
        r->vals[0] = V;
        r->c[0] = root_;
        r->c[1] = R;
        r->n = 1;
        root_ = r;
        height_++;
        return true;
    }

    bool remove(std::int64_t key) {
        if (!root_) return false;
        Leaf* path[MAXH];
        int idx[MAXH];
        Leaf* x = root_;
        const int H = height_;
        int d = 0;
        unsigned i;
        for (;;) {
            i = lowerBound(x->keys, key);
            path[d] = x;
            if ((int)i < x->n && x->keys[i] == key) break;
            if (d == H - 1) return false;
            idx[d] = (int)i;
            x = in(x)->c[i];
            __builtin_prefetch(reinterpret_cast<const char*>(x) + 128);
            d++;
        }
        if (d == H - 1) {
            int n = x->n - 1;
            std::memmove(x->keys + i, x->keys + i + 1, (n - i) * sizeof(i64));
            std::memmove(x->vals + i, x->vals + i + 1, (n - i) * sizeof(i64));
            x->keys[n] = KMAX;
            x->n = n;
        } else {
            // replace with predecessor (max of left subtree)
            Leaf* target = x;
            idx[d] = (int)i;
            x = in(x)->c[i];
            d++;
            while (d < H - 1) {
                path[d] = x;
                idx[d] = x->n;
                x = in(x)->c[x->n];
                d++;
            }
            path[d] = x;
            int n = x->n - 1;
            target->keys[i] = x->keys[n];
            target->vals[i] = x->vals[n];
            x->keys[n] = KMAX;
            x->n = n;
        }
        count_--;
        // fix underflow bottom-up
        if (d > 0 && path[d]->n < MINK) {
            Inner* p = in(path[d - 1]);
            int ci = idx[d - 1];
            bool merged = rebalance<false>(p, ci > 0 ? ci - 1 : 0);
            d--;
            while (merged && d > 0 && path[d]->n < MINK) {
                p = in(path[d - 1]);
                ci = idx[d - 1];
                merged = rebalance<true>(p, ci > 0 ? ci - 1 : 0);
                d--;
            }
        }
        if (root_->n == 0) {
            Leaf* old = root_;
            if (height_ == 1) {
                root_ = nullptr;
                leafPool_.release(old);
            } else {
                root_ = in(old)->c[0];
                innerPool_.release(old);
            }
            height_--;
        }
        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 || !root_) return 0;
        std::size_t cnt = 0;
        rangeRec(root_, height_, true, lo, hi, out_keys, out_vals, cnt, limit);
        return cnt;
    }

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