重要概念:堆(heap)——是其元素具有键并且满足以下“堆性质”的完全二叉树:从根到叶节点的任何路径上的键都是非增的。堆用于实现优先级队列,因为其允许O(lg N)次插入和删除,这是由于push()和pop()函数是通过遍历穿过堆的从根到叶节点的路径实现的,这种路径并不比树的高度长,它至多是(lg N)。
#ifndef MYPRIORITYQUEUE_H
#define MYPRIORITYQUEUE_H
#include<algorithm>
#include <vector>
using namespace std;
template <class T>
class PriorityQueue
{
public:
PriorityQueue() {}
PriorityQueue(const PriorityQueue& q):val(q.val) {}
~PriorityQueue() {}
PriorityQueue& operator = (const PriorityQueue& q)
{
val.clear();
val = q.val;
}
int size() const {return val.size();}
bool empty() const {return val.empty();}
const T& top() const {return val.front();}
void push(const T&);
void pop();
protected:
private:
vector<T> val;
void heapifyDown(); //从堆顶往下重新存储元素,若堆顶元素小于子元素则交换,若两个子元素均满足则与较大者交换
void heapifyUp(); //从堆底往上重新存储元素,若堆底元素大于父元素则交换,直到堆顶
};
template <class T>
void PriorityQueue<T>::heapifyDown()
{
int len = val.size();
for (int i=0; i<len;)
{
int j = i*2 + 1;
if (j<len && val[i]<val[j])
{
if (j+1<len && val[j]<val[j+1])
{
swap(val[i], val[j+1]);
}
else
swap(val[i], val[j]);
i = j;
}
else
{
if (++j<len && val[i]<val[j])
{
swap(val[i], val[j]);
i = j;
}
else
break;
}
}
}
template <class T>
void PriorityQueue<T>::heapifyUp()
{
int len = val.size();
for (int i = len-1; i > 0;)
{
int j = (i-1)/2;
if (val[i] > val[j])
{
swap(val[i], val[j]);
i = j;
}
else
break;
}
}
template <class T>
void PriorityQueue<T>::push(const T& t)
{
val.push_back(t);
heapifyUp();
}
template <class T>
void PriorityQueue<T>::pop()
{
val.front() = val.back();
val.pop_back(); //删除堆顶元素,用堆底元素替代
heapifyDown();
}
#endif
测试函数:
int _tmain(int argc, _TCHAR* argv[])
{
typedef PriorityQueue<int> PQ;
PQ q1;
q1.push(44);
q1.push(66);
q1.push(33);
q1.push(88);
q1.push(77);
q1.push(55);
q1.push(22);
while (!q1.empty())
{
cout<<q1.top()<<" ";
q1.pop();
}
return 0;
}
存储数组:88 77 55 44 66 33 22
输出结果:88 77 66 55 44 33 22