/**
 * Array-based binary min-heap of (long key, long value) entries.
 *
 * Layout: one interleaved long[] array; tree position i keeps its key at
 * a[2i] and its value at a[2i+1], so an entry (and a sibling pair) lives in
 * one cache line and a single miss fetches both key and value.
 *
 * Entries are ordered by key, then by value (signed 64-bit comparisons).
 */
public final class Heap {
    private static final int INIT_CAP = 64;          // entries
    private static final int MAX_CAP = (Integer.MAX_VALUE - 16) >>> 1;
    // Subtrees with at most this many internal levels are heapified as a
    // block (level by level) so that their working set stays in L2.
    private static final int BLOCK_LEVELS = 14;

    private long[] a;
    private int n;
    // Sink for the touch-ahead loads used as software prefetches, so the JIT
    // cannot drop them.
    private long sink;

    public Heap() {
        a = new long[INIT_CAP * 2];
    }

    public Heap(long[] keys, long[] values, int count) {
        int cap = Math.max(count, 16);
        long[] a = new long[cap * 2];
        for (int i = 0, j = 0; i < count; i++, j += 2) {
            a[j] = keys[i];
            a[j + 1] = values[i];
        }
        this.a = a;
        this.n = count;
        if (count > 1) buildRec(0, (count >>> 1) - 1);
    }

    // ------------------------------------------------------------- build

    private void buildRec(int r, int lastInternal) {
        int levels = 0;
        long lo = r;
        while (lo <= lastInternal) {
            levels++;
            lo = 2 * lo + 1;
        }
        if (levels == 0) return;
        if (levels > BLOCK_LEVELS) {
            buildRec(2 * r + 1, lastInternal);
            buildRec(2 * r + 2, lastInternal);
            siftDownBuild(r);
            return;
        }
        for (int d = levels - 1; d >= 0; d--) {
            long start = ((long) (r + 1) << d) - 1;
            long end = Math.min(start + (1L << d) - 1, lastInternal);
            for (int i = (int) end; i >= start; i--) siftDownBuild(i);
        }
    }

    /** Floyd's bottom-up sift-down of the entry at i, bounded above by i. */
    private void siftDownBuild(int i) {
        final long[] a = this.a;
        final int n = this.n;
        final long xk = a[2 * i], xv = a[2 * i + 1];
        int h = i;
        int c = 2 * h + 1;
        final int lastPair = n - 1;
        while (c < lastPair) {
            int j = 2 * c;
            long lk = a[j], lv = a[j + 1], rk = a[j + 2], rv = a[j + 3];
            boolean r = rk < lk | (rk == lk & rv < lv);
            long ck = r ? rk : lk;
            long cv = r ? rv : lv;
            c = r ? c + 1 : c;
            a[2 * h] = ck;
            a[2 * h + 1] = cv;
            h = c;
            c = 2 * h + 1;
        }
        if (c == lastPair) {
            a[2 * h] = a[2 * c];
            a[2 * h + 1] = a[2 * c + 1];
            h = c;
        }
        while (h > i) {
            int p = (h - 1) >>> 1;
            long pk = a[2 * p], pv = a[2 * p + 1];
            if (!(xk < pk || (xk == pk && xv < pv))) break;
            a[2 * h] = pk;
            a[2 * h + 1] = pv;
            h = p;
        }
        a[2 * h] = xk;
        a[2 * h + 1] = xv;
    }

    // -------------------------------------------------------- operations

    public void push(long key, long value) {
        int h = n;
        if (h == (a.length >>> 1)) grow();
        final long[] a = this.a;
        n = h + 1;
        while (h > 0) {
            int p = (h - 1) >>> 1;
            long pk = a[2 * p], pv = a[2 * p + 1];
            if (!(key < pk || (key == pk && value < pv))) break;
            a[2 * h] = pk;
            a[2 * h + 1] = pv;
            h = p;
        }
        a[2 * h] = key;
        a[2 * h + 1] = value;
    }

    public boolean peek(long[] out) {
        if (n == 0) return false;
        out[0] = a[0];
        out[1] = a[1];
        return true;
    }

    public boolean pop(long[] out) {
        int n = this.n;
        if (n == 0) return false;
        final long[] a = this.a;
        out[0] = a[0];
        out[1] = a[1];
        n--;
        this.n = n;
        if (n == 0) return true;
        final long xk = a[2 * n], xv = a[2 * n + 1];

        // Move the hole at the root down to a leaf along the smaller children.
        final int pfMax = (a.length - 29) >> 4;
        long pf = 0;
        int h = 0;
        int c = 1;
        final int lastPair = n - 1;
        while (c < lastPair) {
            if (h <= pfMax) pf ^= a[16 * h + 14] ^ a[16 * h + 28];
            int j = 2 * c;
            long lk = a[j], lv = a[j + 1], rk = a[j + 2], rv = a[j + 3];
            boolean r = rk < lk | (rk == lk & rv < lv);
            long ck = r ? rk : lk;
            long cv = r ? rv : lv;
            c = r ? c + 1 : c;
            a[2 * h] = ck;
            a[2 * h + 1] = cv;
            h = c;
            c = 2 * h + 1;
        }
        if (c == lastPair) {
            a[2 * h] = a[2 * c];
            a[2 * h + 1] = a[2 * c + 1];
            h = c;
        }
        sink = pf;
        // Sift the former last entry up from the leaf hole.
        while (h > 0) {
            int p = (h - 1) >>> 1;
            long pk = a[2 * p], pv = a[2 * p + 1];
            if (!(xk < pk || (xk == pk && xv < pv))) break;
            a[2 * h] = pk;
            a[2 * h + 1] = pv;
            h = p;
        }
        a[2 * h] = xk;
        a[2 * h + 1] = xv;
        return true;
    }

    public boolean replace(long key, long value, long[] out) {
        if (n == 0) {
            push(key, value);
            return false;
        }
        out[0] = a[0];
        out[1] = a[1];
        siftDownRoot(key, value);
        return true;
    }

    public void pushPop(long key, long value, long[] out) {
        if (n != 0) {
            long rk = a[0], rv = a[1];
            if (rk < key || (rk == key && rv < value)) {
                out[0] = rk;
                out[1] = rv;
                siftDownRoot(key, value);
                return;
            }
        }
        out[0] = key;
        out[1] = value;
    }

    /** Top-down sift-down of (xk, xv) placed at the root, stopping early. */
    private void siftDownRoot(long xk, long xv) {
        final long[] a = this.a;
        final int n = this.n;
        final int pfMax = (a.length - 29) >> 4;
        long pf = 0;
        int h = 0;
        int c = 1;
        while (c < n) {
            if (h <= pfMax) pf ^= a[16 * h + 14] ^ a[16 * h + 28];
            int j = 2 * c;
            long ck = a[j], cv = a[j + 1];
            if (c + 1 < n) {
                long rk = a[j + 2], rv = a[j + 3];
                boolean r = rk < ck | (rk == ck & rv < cv);
                ck = r ? rk : ck;
                cv = r ? rv : cv;
                c = r ? c + 1 : c;
            }
            if (!(ck < xk || (ck == xk && cv < xv))) break;
            a[2 * h] = ck;
            a[2 * h + 1] = cv;
            h = c;
            c = 2 * h + 1;
        }
        sink = pf;
        a[2 * h] = xk;
        a[2 * h + 1] = xv;
    }

    public int size() {
        return n;
    }

    public void slot(int i, long[] out) {
        out[0] = a[2 * i];
        out[1] = a[2 * i + 1];
    }

    private void grow() {
        int cap = a.length >>> 1;
        if (cap >= MAX_CAP) throw new OutOfMemoryError("heap too large");
        int newCap = cap > MAX_CAP / 2 ? MAX_CAP : Math.max(cap * 2, INIT_CAP);
        long[] na = new long[newCap * 2];
        System.arraycopy(a, 0, na, 0, n * 2);
        a = na;
    }
}
