#pragma once #include #include template < typename T, typename Array = QVector, typename compare_T=std::less > class PriorityQueue { public: PriorityQueue(); bool empty(); T front(); void push(const T& val); void pop(); int size(); private: void up_adjust(); // 向上调整 void down_adjust(); // 向下调整 Array elements; compare_T compare; }; template PriorityQueue::PriorityQueue() { elements.clear(); } template bool PriorityQueue::empty() { return elements.size() == 0; } template T PriorityQueue::front() { return elements[0]; } template void PriorityQueue::push(const T &val) { elements.push_back(val); up_adjust(); } template void PriorityQueue::pop() { if (empty()) return; int count = elements.size(); qSwap(elements[count - 1], elements[0]); elements.pop_back(); down_adjust(); } template int PriorityQueue::size() { return elements.size(); } template void PriorityQueue::up_adjust() { int ind = elements.size(); while (ind > 1 && compare(elements[ind/2-1], elements[ind-1])) { qSwap(elements[ind/2-1], elements[ind-1]); ind /= 2; } } template void PriorityQueue::down_adjust() { int ind = 0; int count = elements.size(); while (ind * 2 + 1 < count) { int tind = ind; if (compare(elements[tind], elements[ind*2+1])) tind = ind * 2 + 1; if (ind*2+2