#pragma once #include #include template class Heap { public: void Push(const Key &k, const Val &v); Val Pop(); size_t Size() const; bool Empty() const; protected: std::vector < std::pair > h; }; template size_t Heap::Size() const { return h.size(); } template bool Heap::Empty() const { return h.empty(); } template void Heap::Push(const Key &k, const Val &v) { int i, parent; std::pair tmp; h.push_back(std::make_pair(k, v)); i = h.size()-1; while (1) { if (i == 0) return; parent = (i-1)/2; if (h[parent].first > h[i].first) { tmp = h[i]; h[i] = h[parent]; h[parent] = tmp; i = parent; } else { return; } } } template Val Heap::Pop() { Val retval; std::pair tmp; size_t lc, rc; int index; if (h.empty()) throw (std::string) "Called Pop() on an empty heap"; retval = h[0].second; h[0] = h[h.size()-1]; h.pop_back(); if (h.size() == 0) return retval; index = 0; while (1) { lc = index*2+1; rc = lc+1; if (lc >= h.size()) return retval; if (rc == h.size() || h[lc].first <= h[rc].first) { if (h[lc] < h[index]) { tmp = h[lc]; h[lc] = h[index]; h[index] = tmp; index = lc; } else { return retval; } } else if (h[rc] < h[index]) { tmp = h[rc]; h[rc] = h[index]; h[index] = tmp; index = rc; } else { return retval; } } }