// Randomized skip list (Pugh, 1990): ordered map i64 -> i64.
//
// Node layout (one contiguous block per entry, no height field):
//
//     [ value | key | next[0] | next[1] | ... | next[h-1] ]
//                ^
//                Node* points here
//
// The key and the level-0 link are adjacent, so a level-0 step touches one
// cache line; the value sits just before the key and is read only on a hit.
// A node's height is not stored: remove() recovers it from the predecessors
// (the levels whose predecessor links to the node).
//
// Heights: p = 1/2, maximum height 32, drawn from a private splitmix64
// generator seeded with a fixed constant.
//
// Memory: per-height size classes, each carved from geometrically growing
// slabs and recycled through a per-class free list. Nodes of the same height
// live together, so the tall (frequently visited) nodes are packed densely
// and stay cache resident.
#pragma once

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

class SkipList {
    static constexpr int kMaxHeight = 32;  // p = 1/2: 2^32 entries
    static constexpr std::size_t kAlign = 128;

    struct Node {
        std::int64_t key;
        Node* next[];  // flexible array: h links
    };

    static inline std::int64_t& val(Node* n) {
        return reinterpret_cast<std::int64_t*>(n)[-1];
    }
    static inline std::int64_t val(const Node* n) {
        return reinterpret_cast<const std::int64_t*>(n)[-1];
    }
    static inline void prefetch(const void* p) { __builtin_prefetch(p, 0, 3); }

    static constexpr std::size_t block_size(int h) {
        return sizeof(std::int64_t) * 2 + sizeof(Node*) * static_cast<std::size_t>(h);
    }

    Node* head_;
    int level_ = 0;  // height of the tallest node, 0 when empty
    std::size_t count_ = 0;
    std::uint64_t rng_ = 0x2545F4914F6CDD1DULL;

    // Per-height allocation pools (index = height, 1..kMaxHeight).
    Node* free_[kMaxHeight + 1] = {};
    char* bump_[kMaxHeight + 1] = {};
    char* bump_end_[kMaxHeight + 1] = {};
    std::size_t chunk_nodes_[kMaxHeight + 1] = {};
    std::vector<void*> chunks_;

    inline int random_height() {
        std::uint64_t z = (rng_ += 0x9E3779B97F4A7C15ULL);
        z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
        z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
        z ^= z >> 31;
        int h = 1 + std::countr_zero(z);
        return h > kMaxHeight ? kMaxHeight : h;
    }

    void* new_chunk(std::size_t bytes) {
        chunks_.reserve(chunks_.size() + 1);
        void* p = ::operator new(bytes, std::align_val_t(kAlign));
        chunks_.push_back(p);
        return p;
    }

    __attribute__((noinline)) void refill(int h) {
        std::size_t nodes = chunk_nodes_[h];
        nodes = nodes == 0 ? 64 : (nodes < (std::size_t(1) << 15) ? nodes * 2 : nodes);
        chunk_nodes_[h] = nodes;
        std::size_t bytes = nodes * block_size(h);
        char* p = static_cast<char*>(new_chunk(bytes));
        bump_[h] = p;
        bump_end_[h] = p + bytes;
    }

    inline Node* alloc_node(int h) {
        Node* n = free_[h];
        if (n) {
            free_[h] = n->next[0];
            return n;
        }
        std::size_t sz = block_size(h);
        if (static_cast<std::size_t>(bump_end_[h] - bump_[h]) < sz) [[unlikely]]
            refill(h);
        char* b = bump_[h];
        bump_[h] = b + sz;
        return reinterpret_cast<Node*>(b + sizeof(std::int64_t));
    }

    inline void free_node(Node* n, int h) {
        n->next[0] = free_[h];
        free_[h] = n;
    }

    // Find, at every level, the last node with key < `key`.
    inline void find_preds(std::int64_t key, Node** upd) const {
        Node* x = head_;
        for (int L = level_ - 1; L >= 1; --L) {
            Node* y = x->next[L];
            prefetch(x->next[L - 1]);
            while (y && y->key < key) {
                x = y;
                y = x->next[L];
                prefetch(x->next[L - 1]);
            }
            upd[L] = x;
        }
        Node* y = x->next[0];
        while (y && y->key < key) {
            x = y;
            y = x->next[0];
        }
        upd[0] = x;
    }

public:
    SkipList() {
        void* p = ::operator new(block_size(kMaxHeight), std::align_val_t(kAlign));
        head_ = reinterpret_cast<Node*>(static_cast<char*>(p) + sizeof(std::int64_t));
        head_->key = 0;
        for (int i = 0; i < kMaxHeight; ++i) head_->next[i] = nullptr;
    }

    ~SkipList() {
        for (void* c : chunks_) ::operator delete(c, std::align_val_t(kAlign));
        ::operator delete(reinterpret_cast<char*>(head_) - sizeof(std::int64_t),
                          std::align_val_t(kAlign));
    }

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

    bool insert(std::int64_t key, std::int64_t value) {
        Node* upd[kMaxHeight];
        find_preds(key, upd);
        Node* c = upd[0]->next[0];
        if (c && c->key == key) {
            val(c) = value;
            return false;
        }
        int h = random_height();
        if (h > level_) {
            for (int i = level_; i < h; ++i) upd[i] = head_;
            level_ = h;
        }
        Node* n = alloc_node(h);
        n->key = key;
        val(n) = value;
        for (int i = 0; i < h; ++i) {
            n->next[i] = upd[i]->next[i];
            upd[i]->next[i] = n;
        }
        ++count_;
        return true;
    }

    std::optional<std::int64_t> get(std::int64_t key) const {
        Node* x = head_;
        for (int L = level_ - 1; L >= 1; --L) {
            Node* y = x->next[L];
            prefetch(x->next[L - 1]);
            while (y) {
                std::int64_t k = y->key;
                if (k >= key) {
                    if (k == key) return val(y);
                    break;
                }
                x = y;
                y = x->next[L];
                prefetch(x->next[L - 1]);
            }
        }
        Node* y = x->next[0];
        while (y && y->key < key) y = y->next[0];
        if (y && y->key == key) return val(y);
        return std::nullopt;
    }

    bool remove(std::int64_t key) {
        Node* upd[kMaxHeight];
        find_preds(key, upd);
        Node* c = upd[0]->next[0];
        if (!c || c->key != key) return false;
        int h = 0;
        while (h < level_ && upd[h]->next[h] == c) {
            upd[h]->next[h] = c->next[h];
            ++h;
        }
        free_node(c, h);
        while (level_ > 0 && head_->next[level_ - 1] == nullptr) --level_;
        --count_;
        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;

        // Prefetch runners: runner L walks level L up to kAhead hops in front
        // of the scan, prefetching its next node at level L and at level L-1,
        // so the level-0 scan mostly finds its nodes already in cache.
        constexpr int K = 3;
        constexpr int kAhead = 8;
        constexpr int kSteps = 2;

        Node* first[K + 1] = {};
        Node* x = head_;
        for (int L = level_ - 1; L >= 1; --L) {
            Node* y = x->next[L];
            prefetch(x->next[L - 1]);
            while (y && y->key < lo) {
                x = y;
                y = x->next[L];
                prefetch(x->next[L - 1]);
            }
            if (L <= K) first[L] = y;
        }
        x = x->next[0];
        while (x && x->key < lo) x = x->next[0];
        if (!x || x->key > hi) return 0;

        Node* cur[K + 1];  // first level-L node at or after x
        Node* run[K + 1];  // runner position at level L
        int ahead[K + 1];  // hops run[L] is in front of cur[L]
        constexpr int kDone = 1 << 30;

        auto advance = [&](int L) {
            for (int s = 0; s < kSteps && ahead[L] < kAhead; ++s) {
                Node* z = run[L];
                if (!z || z->key > hi) {
                    ahead[L] = kDone;
                    return;
                }
                prefetch(z->next[L - 1]);
                Node* nz = z->next[L];
                prefetch(nz);
                run[L] = nz;
                ++ahead[L];
            }
        };

        for (int L = 1; L <= K; ++L) {
            cur[L] = first[L];
            run[L] = first[L];
            ahead[L] = 0;
            advance(L);
        }

        std::size_t n = 0;
        for (;;) {
            out_keys[n] = x->key;
            out_vals[n] = val(x);
            if (++n == limit) break;
            if (x == cur[1]) {
                for (int L = 1; L <= K; ++L) {
                    if (x != cur[L]) break;
                    Node* c = x->next[L];
                    cur[L] = c;
                    if (ahead[L] > 0) {
                        if (ahead[L] != kDone) --ahead[L];
                    } else {
                        run[L] = c;
                    }
                    if (ahead[L] != kDone) advance(L);
                }
            }
            x = x->next[0];
            if (!x || x->key > hi) break;
        }
        return n;
    }

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

    std::size_t height() const { return static_cast<std::size_t>(level_); }

    std::size_t level_count(std::size_t level) const {
        if (level >= static_cast<std::size_t>(level_)) return 0;
        std::size_t c = 0;
        for (Node* x = head_->next[level]; x; x = x->next[level]) ++c;
        return c;
    }
};
