1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| using namespace std;
typedef unsigned long ul; template<class > class BinaryHeap{ public: BinaryHeap(); explicit BinaryHeap(vector<T>); explicit BinaryHeap(bool (*cmp)(const T&, const T&)); explicit BinaryHeap(vector<T>,bool (*cmp)(const T&, const T&));
bool insert(T ele); void show_queue(){ for(T x : elements){ cout << x << " "; } cout << endl; } T pop_top(); bool empty(); private: vector<T> elements; unsigned long heap_size; bool (*cmp)(T ele_a, T ele_b);
void shift_up(T, ul); void shift_down(T, ul); bool build_heap(); static bool default_cmp(T ele_a, T ele_b); };
template<class > BinaryHeap<T>::BinaryHeap() { heap_size = 0; this->cmp = default_cmp; } template<class > BinaryHeap<T>::BinaryHeap(bool (*cmp)(const T&, const T&)) { heap_size = 0; this->cmp = cmp; } template<class > BinaryHeap<T>::BinaryHeap(vector<T> eles):elements(move(eles)) { heap_size = elements.size(); this->cmp = default_cmp; build_heap(); }
template<class > BinaryHeap<T>::BinaryHeap(vector<T> eles, bool (*cmp)(const T&, const T&)):elements(move(eles)){ heap_size = elements.size(); build_heap(); this->cmp = cmp; }
template<class T> bool BinaryHeap<T>::insert(T ele) { elements.push_back(ele); heap_size++;
shift_up(ele,heap_size-1);
return true; }
template<class T> T BinaryHeap<T>::pop_top() { if(heap_size <= 0) throw exception();
T leave = elements[--heap_size]; T top = elements[0]; elements.pop_back();
if(heap_size > 1) shift_down(leave,0); return top; }
template<class T> bool BinaryHeap<T>::empty() { return heap_size == 0; }
template<class T> bool BinaryHeap<T>::build_heap() { if(heap_size == 0) return true;
unsigned long _first_not_leave = (heap_size - 1) / 2; for(ul i = _first_not_leave; i >= 0;i--){ shift_down(elements[i],i); if(i == 0) break; } } template<class T> bool BinaryHeap大专栏 Priority Queue Implementationn><T>::default_cmp(T ele_a, T ele_b) { return ele_a < ele_b; }
template<class T> void BinaryHeap<T>::shift_up(T ele, ul pos) { ul i = pos,j = (pos - 1) / 2; while(i > 0 and cmp(ele,elements[j])){ elements[i] = elements[j]; i = j;j = (i - 1) / 2; } elements[i] = ele; } template<class T> void BinaryHeap<T>::shift_down(T ele, ul pos) { ul i = pos, j = pos * 2 + 1; while(j < heap_size){ if(j+1 < heap_size && cmp(elements[j+1],elements[j])) j = j+1; if(cmp(ele,elements[j])) break; elements[i] = elements[j]; i = j; j = i*2 + 1; } elements[i] = ele; } int main() {
vector<int> v{4,6,8,7,4,2,4}; auto *hp = new BinaryHeap<int>(v);
while(!hp->empty()){ cout << hp->pop_top() <<" "; } cout << endl; return 0; }
|