// Array-based binary min-heap (Williams 1964 / CLRS ch. 6).
//
// Layout: one contiguous array of 16-byte nodes. Tree position p (0-based,
// root 0, children 2p+1 / 2p+2) is stored at array index p + 1, so the root
// sits at index 1 and the children of index m are 2m and 2m+1. With the
// array 128-byte aligned this keeps every sibling pair in one 32-byte chunk
// and the 8 great-grandchildren of m (indices 8m..8m+7) in exactly one
// cache line.
//
// Each node is a signed 128-bit integer: high 64 bits = key (signed), low
// 64 bits = value with its sign bit flipped. Signed 128-bit comparison of
// that encoding is exactly the (key, value) lexicographic order on signed
// 64-bit integers, so every comparison is a branch-free cmp/sbcs pair.
#pragma once

#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <new>
#include <optional>

struct Entry {
    std::int64_t key;
    std::int64_t value;
};

class Heap {
    using node = __int128;
    static constexpr std::uint64_t SIGN = 0x8000000000000000ULL;

    node* h_ = nullptr;        // h_[1 .. n_] hold the entries; h_[0] unused
    std::size_t n_ = 0;        // number of entries
    std::size_t cap_ = 0;      // usable slots (array has cap_ + 1 nodes)

    static inline node enc(std::int64_t k, std::int64_t v) {
        return (node)(((unsigned __int128)(std::uint64_t)k << 64) |
                      (unsigned __int128)((std::uint64_t)v ^ SIGN));
    }
    static inline Entry dec(node x) {
        return Entry{(std::int64_t)(x >> 64),
                     (std::int64_t)((std::uint64_t)(unsigned __int128)x ^ SIGN)};
    }

    static inline void prefetch_at(const node* h, std::size_t idx) {
        __builtin_prefetch((const void*)((std::uintptr_t)h + idx * sizeof(node)), 1, 3);
    }

    // Grow so that at least `need` entries fit. Doubling: amortised O(1).
    // realloc lets the system allocator remap pages for large blocks instead
    // of copying them; blocks above ~1 KB are at least 512-byte aligned on
    // this platform, which only matters for speed, never for correctness.
    __attribute__((noinline)) void grow(std::size_t need) {
        std::size_t nc = cap_ ? cap_ * 2 : 127;
        while (nc < need) nc = nc * 2 + 1;
        void* p = std::realloc((void*)h_, (nc + 1) * sizeof(node));
        if (!p) throw std::bad_alloc();
        h_ = (node*)p;
        cap_ = nc;
    }

    // Hole at index m in a heap of n entries; place x somewhere on the path
    // below/above m. Bottom-up (Floyd): walk the hole to a leaf along the
    // smaller children (one comparison per level, branch-free), then sift x up.
    static inline void sift_hole_bottom_up(node* h, std::size_t n, std::size_t m, node x) {
        const std::size_t start = m;
        const std::size_t pf_lim = n >> 4;
        std::size_t c;
        while ((c = 2 * m) < n) {
            if (m <= pf_lim) {
                prefetch_at(h, 16 * m);
                prefetch_at(h, 16 * m + 8);
            }
            node a = h[c], b = h[c + 1];
            bool r = b < a;
            c += r;
            h[m] = r ? b : a;
            m = c;
        }
        if (c == n) {
            h[m] = h[c];
            m = c;
        }
        while (m > start) {
            std::size_t p = m >> 1;
            node hp = h[p];
            if (!(x < hp)) break;
            h[m] = hp;
            m = p;
        }
        h[m] = x;
    }

    // Top-down sift with early exit: used by replace/push_pop, where the
    // new entry often settles above the (uncached) bottom levels.
    static inline void sift_hole_top_down(node* h, std::size_t n, std::size_t m, node x) {
        const std::size_t pf_lim = n >> 4;
        std::size_t c;
        while ((c = 2 * m) < n) {
            if (m <= pf_lim) {
                prefetch_at(h, 16 * m);
                prefetch_at(h, 16 * m + 8);
            }
            node a = h[c], b = h[c + 1];
            bool r = b < a;
            c += r;
            node mc = r ? b : a;
            if (!(mc < x)) {
                h[m] = x;
                return;
            }
            h[m] = mc;
            m = c;
        }
        if (c == n) {
            node hc = h[c];
            if (hc < x) {
                h[m] = hc;
                m = c;
            }
        }
        h[m] = x;
    }

public:
    Heap() { grow(1); }

    Heap(const std::int64_t* keys, const std::int64_t* values, std::size_t count) {
        grow(count);
        node* h = h_;
        for (std::size_t i = 0; i < count; i++) h[i + 1] = enc(keys[i], values[i]);
        n_ = count;
        for (std::size_t m = count >> 1; m >= 1; m--) {
            node x = h[m];
            sift_hole_bottom_up(h, count, m, x);
        }
    }

    ~Heap() { std::free((void*)h_); }

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

    inline void push(std::int64_t key, std::int64_t value) {
        node x = enc(key, value);
        std::size_t m = n_ + 1;
        if (__builtin_expect(m > cap_, 0)) grow(m);
        n_ = m;
        node* h = h_;
        while (m > 1) {
            std::size_t p = m >> 1;
            node hp = h[p];
            if (!(x < hp)) break;
            h[m] = hp;
            m = p;
        }
        h[m] = x;
    }

    inline std::optional<Entry> peek() const {
        if (n_ == 0) return std::nullopt;
        return dec(h_[1]);
    }

    inline std::optional<Entry> pop() {
        std::size_t n = n_;
        if (n == 0) return std::nullopt;
        node* h = h_;
        node top = h[1];
        node last = h[n];
        n--;
        n_ = n;
        if (n != 0) sift_hole_bottom_up(h, n, 1, last);
        return dec(top);
    }

    inline std::optional<Entry> replace(std::int64_t key, std::int64_t value) {
        if (n_ == 0) {
            push(key, value);
            return std::nullopt;
        }
        node* h = h_;
        node top = h[1];
        sift_hole_top_down(h, n_, 1, enc(key, value));
        return dec(top);
    }

    inline Entry push_pop(std::int64_t key, std::int64_t value) {
        node x = enc(key, value);
        if (n_ == 0) return Entry{key, value};
        node* h = h_;
        node top = h[1];
        if (!(top < x)) return Entry{key, value};
        sift_hole_top_down(h, n_, 1, x);
        return dec(top);
    }

    inline std::size_t len() const { return n_; }

    inline Entry slot(std::size_t i) const { return dec(h_[i + 1]); }
};
