优先级队列
优先级队列首先是一个队列,但是它强调的是“优先”,所以优先级队列又分为最大优先队列和最小优先队列。
最大优先级队列:每次从队列中取出优先级最大的数据,删除数据也是删除优先级最大的数据。
最小优先级队列:每次从队列中取出优先级最小的数据,删除也是删除优先级最小的数据。
所以我们用一个类去实现优先级队列时就需要用到小顶堆和大顶堆的概念。我们并不关心除了最高优先级和最低优先级的数据在队列中是怎体存储的。
为了提高代码的复用性,最大优先级对列和最小优先级队列都使用同一个堆调整函数,我们可以定义一个比较模板(Compare)也可以说是一个类,不过它是通过重载()实现的。
template<classT>structLess{booloperator()(constT&left,constT&right)returnleft<right;};template<classT>structGreater{booloperator()(constT&left,constT&right)returnleft>right;};
通过Less和Grearter模板,我们就可以在优先级队列初始化的时候通过传Less或者Greater的对象,来调整是最大优先级队列还是最小优先级队列。
我们的优先级队列所拥有的功能和STL源码的功能差不多。在这我是用一个顺序表来实现队列。以下是具体的实现
#pragmaonce#include<iostream>#include<vector>usingnamespacestd;template<classT>structLess{booloperator()(constT&left,constT&right){return(left<right);}};template<classT>structGreater{booloperator()(constT&left,constT&right){return(left>right);}};template<classT,template<class>classCompare=Less>classPQueue{public:PQueue():_size(0){}PQueue(constT*a,size_tsize):_size(size){_data.resize(size);for(size_ti=0;i<size;i++){_data[i]=a[i];}for(inti=(size-2)/2;i>=0;--i){_AdjustDown(i);}}size_tSize(){return_size;}voidPush(constT&d){_data.push_back(d);++_size;_AdjustUp();}voidPop(){swap(_data[0],_data[_size-1]);_data.pop_back();_AdjustDown(0);}T&Front(){return_data[0];}boolEmpty(){return_size;}protected:void_AdjustDown(intparent){Compare<T>con;intchild=parent*2+1;while(child<_size){if(child+1<_size&&con(_data[child+1],_data[child]))++child;if(con(_data[child],_data[parent])){swap(_data[child],_data[parent]);parent=child;child=parent*2+1;}elsebreak;}}void_AdjustUp(intchild){Compare<T>con;parent=(child-1)/2;while(child>0){if(con(_data[child],_data[parent])){swap(_data[child],_data[parent]);child=parent;parent=(child-1)/2;}elsebreak;}}protected:vector<T>_data;size_t_size;};
优先级队列的核心就是调整大顶堆和小顶堆,如果对于大顶堆和小顶堆有不懂得话可以查看我的博客,互相交流学习。http://helloleex.blog.51cto.com/10728491/1768758
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。