const std = @import("std");

pub const Entry = struct { key: i64, value: i64 };

// Internal representation of an entry: one i128 whose high 64 bits are the
// key and whose low 64 bits are the value with its sign bit flipped. Signed
// comparison of these i128 words is exactly the (key, value) lexicographic
// order, so every comparison is a single 128-bit compare (cmp + sbcs) and
// every move is a single 16-byte load/store pair.
const SIGN: u64 = @as(u64, 1) << 63;

inline fn enc(k: i64, v: i64) i128 {
    return (@as(i128, k) << 64) | @as(i128, @as(u64, @bitCast(v)) ^ SIGN);
}

inline fn dec(x: i128) Entry {
    const u: u128 = @bitCast(x);
    return .{
        .key = @bitCast(@as(u64, @truncate(u >> 64))),
        .value = @bitCast(@as(u64, @truncate(u)) ^ SIGN),
    };
}

const LINE: usize = 128; // cache line size of the target machine

// Layout: tree position p (0-based) is stored at array index p + 1, so the
// children of array index a are 2a and 2a + 1. The array base is aligned to
// 128 bytes, hence a sibling pair always shares a 32-byte block, and the 8
// great-grandchildren of a (indices 8a .. 8a+7) fill exactly one cache line,
// which sift-down prefetches three levels ahead. Index 0 is unused padding.

inline fn prefetchLine(d: [*]i128, a: usize) void {
    // Address computed as an integer: it may lie past the allocation, which is
    // harmless for a prefetch hint.
    const p: *const u8 = @ptrFromInt(@intFromPtr(d) + a * (8 * @sizeOf(i128)));
    @prefetch(p, .{ .rw = .write, .locality = 3, .cache = .data });
}

inline fn siftUp(d: [*]i128, start: usize, x: i128) void {
    var a = start;
    while (a > 1) {
        const p = a >> 1;
        const pv = d[p];
        if (!(x < pv)) break;
        d[a] = pv;
        a = p;
    }
    d[a] = x;
}

// Place x into the hole at index `start` of a heap whose last index is n.
// Bottom-up (Floyd) strategy: move the hole down to a leaf along the path of
// smaller children (one branchless comparison per level), then sift x up from
// there, never above `start`. Both phases stay on one root-to-leaf path.
inline fn siftDown(d: [*]i128, n: usize, start: usize, x: i128) void {
    var a = start;
    var c = a << 1;
    while (c < n) {
        prefetchLine(d, a);
        const l = d[c];
        const r = d[c + 1];
        const rl = r < l;
        d[a] = if (rl) r else l;
        a = c + @intFromBool(rl);
        c = a << 1;
    }
    if (c == n) {
        d[a] = d[c];
        a = c;
    }
    while (a > start) {
        const p = a >> 1;
        const pv = d[p];
        if (!(x < pv)) break;
        d[a] = pv;
        a = p;
    }
    d[a] = x;
}

pub const Heap = struct {
    data: [*]i128, // 128-byte aligned; positions live at indices 1 .. n
    n: usize,
    cap: usize, // usable indices 1 .. cap
    raw_ptr: [*]u8,
    raw_len: usize,
    allocator: std.mem.Allocator,

    pub fn init(allocator: std.mem.Allocator) Heap {
        return .{
            .data = undefined,
            .n = 0,
            .cap = 0,
            .raw_ptr = undefined,
            .raw_len = 0,
            .allocator = allocator,
        };
    }

    pub fn build(allocator: std.mem.Allocator, keys: []const i64, values: []const i64) std.mem.Allocator.Error!Heap {
        var h = init(allocator);
        const m = keys.len;
        if (m == 0) return h;
        try h.reserve(@max(m, 15));
        const d = h.data;
        for (keys, values, 1..) |k, v, i| d[i] = enc(k, v);
        h.n = m;
        var i = m >> 1;
        while (i >= 1) : (i -= 1) {
            siftDown(d, m, i, d[i]);
        }
        return h;
    }

    pub fn deinit(self: *Heap) void {
        if (self.raw_len != 0) self.allocator.free(self.raw_ptr[0..self.raw_len]);
        self.* = undefined;
    }

    // Grow so that indices 1 .. new_cap are usable. Bytes are allocated with
    // natural (malloc) alignment so that growth can use realloc in place;
    // the 128-byte aligned base is found inside, and the contents are moved
    // if realloc returned a block with a different misalignment.
    fn reserve(self: *Heap, new_cap: usize) std.mem.Allocator.Error!void {
        const bytes = (new_cap + 1) * @sizeOf(i128) + LINE;
        var m: []u8 = undefined;
        if (self.raw_len == 0) {
            m = try self.allocator.alloc(u8, bytes);
        } else {
            const old_off = @intFromPtr(self.data) - @intFromPtr(self.raw_ptr);
            m = try self.allocator.realloc(self.raw_ptr[0..self.raw_len], bytes);
            const new_off = std.mem.alignForward(usize, @intFromPtr(m.ptr), LINE) - @intFromPtr(m.ptr);
            if (new_off != old_off) {
                const used = (self.n + 1) * @sizeOf(i128);
                @memmove(m[new_off..][0..used], m[old_off..][0..used]);
            }
        }
        const base = std.mem.alignForward(usize, @intFromPtr(m.ptr), LINE);
        self.raw_ptr = m.ptr;
        self.raw_len = m.len;
        self.data = @ptrFromInt(base);
        self.cap = new_cap;
    }

    fn grow(self: *Heap) std.mem.Allocator.Error!void {
        @branchHint(.cold);
        const new_cap = if (self.cap == 0) 15 else self.cap * 2 + 1;
        try self.reserve(new_cap);
    }

    pub fn push(self: *Heap, key: i64, value: i64) std.mem.Allocator.Error!void {
        if (self.n == self.cap) try self.grow();
        const n = self.n + 1;
        self.n = n;
        siftUp(self.data, n, enc(key, value));
    }

    pub fn peek(self: *const Heap) ?Entry {
        if (self.n == 0) return null;
        return dec(self.data[1]);
    }

    pub fn pop(self: *Heap) ?Entry {
        const n = self.n;
        if (n == 0) return null;
        const d = self.data;
        const top = d[1];
        const last = d[n];
        self.n = n - 1;
        siftDown(d, n - 1, 1, last);
        return dec(top);
    }

    pub fn replace(self: *Heap, key: i64, value: i64) std.mem.Allocator.Error!?Entry {
        const n = self.n;
        if (n == 0) {
            @branchHint(.unlikely);
            try self.push(key, value);
            return null;
        }
        const d = self.data;
        const top = d[1];
        siftDown(d, n, 1, enc(key, value));
        return dec(top);
    }

    pub fn pushPop(self: *Heap, key: i64, value: i64) Entry {
        const x = enc(key, value);
        const n = self.n;
        if (n == 0) return .{ .key = key, .value = value };
        const d = self.data;
        const top = d[1];
        if (!(top < x)) return .{ .key = key, .value = value };
        siftDown(d, n, 1, x);
        return dec(top);
    }

    pub fn len(self: *const Heap) usize {
        return self.n;
    }

    pub fn slot(self: *const Heap, i: usize) Entry {
        return dec(self.data[i + 1]);
    }
};
