using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public sealed unsafe class Heap { [StructLayout(LayoutKind.Sequential)] private struct Entry { public long Key; public long Value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public Entry(long key, long value) { Key = key; Value = value; } } // 1-indexed complete binary min-heap in 128-byte aligned native memory: // - _entries[0] holds the sentinel (long.MinValue, long.MinValue) // - Tree position p (0 <= p < _count) is stored at _entries[p + 1] // - Children of index i are 2i and 2i + 1 (always in the same 32B block) // - All 8 great-grandchildren 8i .. 8i + 7 lie in a single 128B cache line private Entry* _entries; private int _count; private int _capacity; private long _pfSink; public Heap() { _entries = null; _count = 0; _capacity = 0; } public Heap(long[] keys, long[] values, int count) { if (count <= 0) { _entries = null; _count = 0; _capacity = 0; return; } // Reserve 25% virtual headroom (untouched pages cost nothing in NativeMemory, // and avoids a full reallocation on workloads like mixed that grow after build). int headroom = (count >> 2) + 16; int bufLen = (count <= int.MaxValue - headroom) ? count + headroom : count + 1; nuint bytes = (nuint)bufLen * (nuint)sizeof(Entry); Entry* arr = (Entry*)NativeMemory.AlignedAlloc(bytes, 128); arr[0] = new Entry(long.MinValue, long.MinValue); _entries = arr; _count = count; _capacity = bufLen - 1; nuint n = (uint)count; fixed (long* kBase = keys) fixed (long* vBase = values) { if (n <= 65536) { CopyRange(arr + 1, kBase, vBase, n); if (n > 1) { HeapifySmall(arr, n); } } else { BuildSubtreeFused(arr, kBase, vBase, n); } } } ~Heap() { Entry* ptr = _entries; if (ptr != null) { _entries = null; NativeMemory.AlignedFree(ptr); } } public int Count { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _count; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Slot(int i, out long key, out long value) { Entry* e = _entries + (uint)(i + 1); key = e->Key; value = e->Value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryPeek(out long key, out long value) { if (_count != 0) { Entry* root = _entries + 1; key = root->Key; value = root->Value; return true; } key = 0; value = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Push(long key, long value) { int count = _count; if (count == _capacity) { Grow(); } int newCount = count + 1; _count = newCount; Entry* arr = _entries; nuint i = (uint)newCount; // Sift up using the sentinel at arr[0] = (long.MinValue, long.MinValue) while (true) { nuint p = i >> 1; Entry* pe = arr + p; long pk = pe->Key; if (key >= pk) { if (key > pk) break; long pv = pe->Value; if (value >= pv) break; arr[i].Key = pk; arr[i].Value = pv; i = p; continue; } arr[i].Key = pk; arr[i].Value = pe->Value; i = p; } arr[i].Key = key; arr[i].Value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryPop(out long key, out long value) { int count = _count; if (count == 0) { key = 0; value = 0; return false; } Entry* arr = _entries; key = arr[1].Key; value = arr[1].Value; int newCount = count - 1; _count = newCount; if (newCount == 0) { return true; } // Load last entry early so any miss overlaps with the sift-down long lastK = arr[(uint)count].Key; long lastV = arr[(uint)count].Value; nuint n = (uint)newCount; // Floyd's sift-down: sift hole all the way to a leaf (1 compare/level), // then sift the last entry up (typically 0-2 steps). nuint i = 1; nuint left = 2; if (n > 2048) { nuint pfLimit = n >> 3; long pf = 0; while (i <= pfLimit) { pf ^= arr[i << 3].Key; Entry* lPtr = arr + left; long lk = lPtr[0].Key; long rk = lPtr[1].Key; nuint isRight = Unsafe.BitCast(rk < lk); if (rk == lk) { isRight = Unsafe.BitCast(lPtr[1].Value < lPtr[0].Value); } arr[i] = lPtr[isRight]; i = left + isRight; left = i << 1; } _pfSink = pf; } while (left < n) { Entry* lPtr = arr + left; long lk = lPtr[0].Key; long rk = lPtr[1].Key; nuint isRight = Unsafe.BitCast(rk < lk); if (rk == lk) { isRight = Unsafe.BitCast(lPtr[1].Value < lPtr[0].Value); } arr[i] = lPtr[isRight]; i = left + isRight; left = i << 1; } if (left == n) { arr[i] = arr[n]; i = n; } // Sift (lastK, lastV) up from leaf i using sentinel at arr[0] while (true) { nuint p = i >> 1; Entry* pe = arr + p; long pk = pe->Key; if (lastK >= pk) { if (lastK > pk) break; long pv = pe->Value; if (lastV >= pv) break; arr[i].Key = pk; arr[i].Value = pv; i = p; continue; } arr[i].Key = pk; arr[i].Value = pe->Value; i = p; } arr[i].Key = lastK; arr[i].Value = lastV; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryReplace(long key, long value, out long oldKey, out long oldValue) { int count = _count; if (count == 0) { if (_capacity == 0) { Grow(); } Entry* a = _entries; a[1].Key = key; a[1].Value = value; _count = 1; oldKey = 0; oldValue = 0; return false; } Entry* arr = _entries; oldKey = arr[1].Key; oldValue = arr[1].Value; SiftDownRoot(arr, (uint)count, key, value); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void PushPop(long key, long value, out long outKey, out long outValue) { int count = _count; if (count == 0) { outKey = key; outValue = value; return; } Entry* arr = _entries; long rk = arr[1].Key; if (key <= rk) { if (key < rk || value <= arr[1].Value) { outKey = key; outValue = value; return; } } outKey = rk; outValue = arr[1].Value; SiftDownRoot(arr, (uint)count, key, value); } // Standard sift-down from root with branchless child selection, early exit, // and 3-level-ahead (8*i) cache-line prefetching for large heaps. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SiftDownRoot(Entry* arr, nuint n, long key, long value) { nuint i = 1; nuint left = 2; if (n > 2048) { nuint pfLimit = n >> 3; long pf = 0; while (i <= pfLimit) { pf ^= arr[i << 3].Key; Entry* lPtr = arr + left; long lk = lPtr[0].Key; long rk = lPtr[1].Key; nuint isRight = Unsafe.BitCast(rk < lk); if (rk == lk) { isRight = Unsafe.BitCast(lPtr[1].Value < lPtr[0].Value); } long ck = isRight != 0 ? rk : lk; Entry* cPtr = lPtr + isRight; if (key <= ck) { if (key < ck || value <= cPtr->Value) { _pfSink = pf; arr[i].Key = key; arr[i].Value = value; return; } } arr[i].Key = ck; arr[i].Value = cPtr->Value; i = left + isRight; left = i << 1; } _pfSink = pf; } while (left < n) { Entry* lPtr = arr + left; long lk = lPtr[0].Key; long rk = lPtr[1].Key; nuint isRight = Unsafe.BitCast(rk < lk); if (rk == lk) { isRight = Unsafe.BitCast(lPtr[1].Value < lPtr[0].Value); } long ck = isRight != 0 ? rk : lk; Entry* cPtr = lPtr + isRight; if (key <= ck) { if (key < ck || value <= cPtr->Value) { arr[i].Key = key; arr[i].Value = value; return; } } arr[i].Key = ck; arr[i].Value = cPtr->Value; i = left + isRight; left = i << 1; } if (left == n) { Entry* cPtr = arr + n; long ck = cPtr->Key; if (ck < key || (ck == key && cPtr->Value < value)) { arr[i].Key = ck; arr[i].Value = cPtr->Value; i = n; } } arr[i].Key = key; arr[i].Value = value; } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow() { int oldCap = _capacity; int newBufLen; if (oldCap == 0) { newBufLen = 128; } else { int oldBufLen = oldCap + 1; if (oldBufLen < 16384) { newBufLen = oldBufLen << 2; } else if (oldBufLen <= (int.MaxValue >> 1)) { newBufLen = oldBufLen << 1; } else { newBufLen = int.MaxValue; } } nuint newBytes = (nuint)newBufLen * (nuint)sizeof(Entry); Entry* next = (Entry*)NativeMemory.AlignedAlloc(newBytes, 128); Entry* old = _entries; if (old != null) { nuint copyBytes = (nuint)(_count + 1) * (nuint)sizeof(Entry); Buffer.MemoryCopy(old, next, newBytes, copyBytes); _entries = next; _capacity = newBufLen - 1; NativeMemory.AlignedFree(old); } else { next[0] = new Entry(long.MinValue, long.MinValue); _entries = next; _capacity = newBufLen - 1; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void CopyRange(Entry* dst, long* kp, long* vp, nuint len) { while (len >= 4) { dst[0].Key = kp[0]; dst[0].Value = vp[0]; dst[1].Key = kp[1]; dst[1].Value = vp[1]; dst[2].Key = kp[2]; dst[2].Value = vp[2]; dst[3].Key = kp[3]; dst[3].Value = vp[3]; dst += 4; kp += 4; vp += 4; len -= 4; } while (len > 0) { dst->Key = *kp; dst->Value = *vp; dst++; kp++; vp++; len--; } } // Bottom-up Floyd heapify for L2-resident heaps (n <= 65536). private static void HeapifySmall(Entry* arr, nuint n) { nuint half = n >> 1; nuint quarter = n >> 2; nuint hi = half; nuint lo = quarter + 1; if ((n & 1) == 0) { SiftLeafParentSingle(arr, hi, n); if (hi > lo) { hi--; for (nuint idx = hi; idx >= lo; idx--) { SiftLeafParentTwo(arr, idx); } } } else { for (nuint idx = hi; idx >= lo; idx--) { SiftLeafParentTwo(arr, idx); } } for (nuint idx = quarter; idx >= 1; idx--) { SiftDownBuild(arr, n, idx); } } // Cache-blocked subtree-fused copy + bottom-up heapify for large heaps (n > 65536). // Each subtree rooted at r in [s, 2s) has <= 32768 entries (<= 512 KB, fitting in L2), // so its entries are copied from (keys, values) and heapified while hot in L2 cache. private static void BuildSubtreeFused(Entry* arr, long* kBase, long* vBase, nuint n) { nuint s = 2; while ((n / s) > 32768) { s <<= 1; } nuint half = n >> 1; bool nIsEven = (n & 1) == 0; nuint rEnd = s << 1; for (nuint r = s; r < rEnd; r++) { int maxD = 0; while ((r << (maxD + 1)) <= n) { maxD++; } // Copy all levels of subtree r into arr (stays resident in L2) for (int d = 0; d <= maxD; d++) { nuint lo = r << d; nuint hi = ((r + 1) << d) - 1; if (hi > n) hi = n; CopyRange(arr + lo, kBase + (lo - 1), vBase + (lo - 1), hi - lo + 1); } // Heapify subtree r bottom-up while hot in L2 for (int d = maxD - 1; d >= 0; d--) { nuint lo = r << d; nuint hi = ((r + 1) << d) - 1; if (hi > half) hi = half; if (lo > hi) continue; if (d == maxD - 1) { if (nIsEven && hi == half) { SiftLeafParentSingle(arr, hi, n); if (hi == lo) continue; hi--; } for (nuint idx = hi; idx >= lo; idx--) { SiftLeafParentTwo(arr, idx); } } else { for (nuint idx = hi; idx >= lo; idx--) { SiftDownBuild(arr, n, idx); } } } } // Copy and heapify the top s - 1 nodes CopyRange(arr + 1, kBase, vBase, s - 1); for (nuint idx = s - 1; idx >= 1; idx--) { SiftDownBuild(arr, n, idx); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SiftLeafParentSingle(Entry* arr, nuint idx, nuint child) { Entry* pPtr = arr + idx; Entry* cPtr = arr + child; long pk = pPtr->Key; long ck = cPtr->Key; if (ck < pk || (ck == pk && cPtr->Value < pPtr->Value)) { Entry tmp = *pPtr; *pPtr = *cPtr; *cPtr = tmp; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SiftLeafParentTwo(Entry* arr, nuint idx) { nuint left = idx << 1; Entry* lPtr = arr + left; long lk = lPtr[0].Key; long rk = lPtr[1].Key; nuint isRight = Unsafe.BitCast(rk < lk); if (rk == lk) { isRight = Unsafe.BitCast(lPtr[1].Value < lPtr[0].Value); } long ck = isRight != 0 ? rk : lk; Entry* pPtr = arr + idx; long pk = pPtr->Key; if (pk < ck) return; Entry* cPtr = lPtr + isRight; if (pk == ck && pPtr->Value <= cPtr->Value) return; Entry tmp = *pPtr; *pPtr = *cPtr; *cPtr = tmp; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SiftDownBuild(Entry* arr, nuint n, nuint i) { nuint left = i << 1; if (left >= n) { if (left == n) { SiftLeafParentSingle(arr, i, n); } return; } // Check first level before extracting (avoids writes when already heap-ordered) Entry* lPtr = arr + left; long lk = lPtr[0].Key; long rk = lPtr[1].Key; nuint isRight = Unsafe.BitCast(rk < lk); if (rk == lk) { isRight = Unsafe.BitCast(lPtr[1].Value < lPtr[0].Value); } long ck = isRight != 0 ? rk : lk; Entry* pPtr = arr + i; long key = pPtr->Key; if (key < ck) return; Entry* cPtr = lPtr + isRight; long value = pPtr->Value; if (key == ck && value <= cPtr->Value) return; pPtr->Key = ck; pPtr->Value = cPtr->Value; i = left + isRight; left = i << 1; while (left < n) { lPtr = arr + left; lk = lPtr[0].Key; rk = lPtr[1].Key; isRight = Unsafe.BitCast(rk < lk); if (rk == lk) { isRight = Unsafe.BitCast(lPtr[1].Value < lPtr[0].Value); } ck = isRight != 0 ? rk : lk; cPtr = lPtr + isRight; if (key <= ck) { if (key < ck || value <= cPtr->Value) { arr[i].Key = key; arr[i].Value = value; return; } } arr[i].Key = ck; arr[i].Value = cPtr->Value; i = left + isRight; left = i << 1; } if (left == n) { cPtr = arr + n; ck = cPtr->Key; if (ck < key || (ck == key && cPtr->Value < value)) { arr[i].Key = ck; arr[i].Value = cPtr->Value; i = n; } } arr[i].Key = key; arr[i].Value = value; } }