// MinStack - 小顶堆 - 开始
template<typename T>
class MinHeap {
int maxHeapSize;
T * heap;
int currentSize;
void shiftDown(int start, int end) {
T temp = heap[start];
while(true) {
int j = 2*start+1;
if(j > end) break;
if(j < end && heap[j] > heap[j+1]) j++;
if(temp <= heap[j]) break;
heap[start] = heap[j];
start = j;
}
heap[start] = temp;
}
void shiftUp(int start) {
T temp = heap[start];
while(start > 0) {
int i = (start-1)/2;
if(heap[i] <= temp) break;
heap[start] = heap[i];
start = i;
}
heap[start] = temp;
}
public:
MinHeap(int size = 10000) {
heap = new T[maxHeapSize = size];
currentSize = 0;
}
~MinHeap() {
delete[] heap;
}
bool isEmpty() {
return currentSize == 0;
}
bool isFull() {
return currentSize == maxHeapSize;
}
void clear() {
currentSize = 0;
}
void insert(T x) {
heap[currentSize] = x;
shiftUp(currentSize++);
}
T remove() {
T x = heap[0];
heap[0] = heap[--currentSize];
shiftDown(0, currentSize-1);
return x;
}
};
// MinStack - 小顶堆 - 结束
template<typename T>
class priority_queue {
std::vector<T> data;
bool (*_comp)(T, T);
public:
priority_queue(bool (*comp)(T, T) = NULL) {
_comp = comp;
}
priority_queue(T *from, T *to, bool (*comp)(T, T) = NULL) {
_comp = comp;
data.assign(from, to);
_comp ? std::make_heap(data.begin(), data.end(), *this)
: std::make_heap(data.begin(), data.end());
}
bool operator() (T a, T b) {
return _comp && _comp(a, b);
}
void push(T t) {
data.push_back(t);
_comp ? std::push_heap(data.begin(), data.end(), *this)
: std::push_heap(data.begin(), data.end());
}
void pop() {
_comp ? std::pop_heap(data.begin(), data.end(), *this)
: std::pop_heap(data.begin(), data.end());
data.pop_back();
}
void sort() {
_comp ? std::sort_heap(data.begin(), data.end(), *this)
: std::sort_heap(data.begin(), data.end());
}
T top() {
return data.front();
}
int size() {
return data.size();
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。