優先級隊列(priority queue) 是0個或多個元素的集合,每個元素都有一個優先權。
一般情況下,查找操作用來搜索優先權最大的元素,刪除操作用來刪除該元素 ,對於優先權相同的元素,可按先進先出次序處理或按任意優先權進行。
由於優先級隊列的性質,我們可以使用堆實現它:
代碼:
Heap.hpp
#include<ostream>
using namespace std;
#include<vector>
#include<assert.h>
template<class T>
struct Less//小堆
{
bool operator()(const T& left,const T& right)
{
return left<right;
}
};
template<class T>
struct Greater//大堆
{
bool operator()(const T& left,const T& right)
{
return left>right;
}
};
template<class T,class Compare=Less<T>>
class Heap
{
public:
Heap()
{}
Heap(const T array[],size_t size)
{
for(int idx=0;idx<size;++idx)
_heap.push_back(array[idx]);
int root=(_heap.size()-2)>>1;//找到倒數第一個非葉子結點·
for(;root>=0;--root)
_AdjustDown(root);
}
size_t Size()const
{
return _heap.size();
}
bool Empty()const
{
return _heap.empty();
}
size_t Top()const
{
return _heap[0];
}
void Insert(const T& data)
{
_heap.push_back(data);//直接插入到最後一個元素
if(_heap.size()>1)//排成最小堆/最大堆
_AdjustUp();
}
void Remove()//刪除堆頂
{
assert(!_heap.empty());
std::swap(_heap[0],_heap[_heap.size()-1]);//將堆頂與最後一個結點交換位置
_heap.pop_back();//最後一個結點出堆,即原來的堆頂
if(_heap.size()>1)
{
int root=(_heap.size()-2)>>1;//找到倒數第一個非葉子結點·
for(;root>=0;--root)
_AdjustDown(root);//將整個樹排爲最小堆/最大堆
}
}
protected:
void _AdjustDown(size_t parent)
{
size_t child=parent*2+1;
size_t size=_heap.size();
while(child<size)
{
Compare com;
if(child+1<size && com(_heap[child+1],_heap[child]))//左孩子>右孩子,將右孩子標記爲孩子結點
child+=1;
if(Compare()(_heap[child],_heap[parent]))//孩子結點<小於雙親結點時,將兩結點交換位置
{
std::swap(_heap[child],_heap[parent]);
parent=child;
child=parent*2+1;
}
else
return;
}
}
void _AdjustUp()//向上排成最小/大堆
{
size_t child=_heap.size()-1;
size_t parent=(child-1)>>1;
while(child!=0)
{
if(Compare()(_heap[child],_heap[parent]))
{
std::swap(_heap[child],_heap[parent]);
child=parent;
parent=(child-1)>>1;
}
else
return;
}
}
private:
std::vector<T> _heap;
};
PriorityQueue.hpp
#include<ostream>
using namespace std;
template<class T, class Compare = Less<T>>
class PriorityQueue
{
public:
PriorityQueue()
{}
PriorityQueue(const T array[],size_t size)
{
_hp=Heap<T,Compare>(array,size);
}
void Push(const T& data)
{
_hp.Insert(data);
}
void Pop()
{
_hp.Remove();
}
const T& Top()const
{
_hp.Top();
}
size_t Size()const
{
return _hp.Size();
}
bool Empty()const
{
return _hp.Empty();
}
protected:
Heap<T, Compare> _hp;
};
測試代碼:
#include"Heap.hpp"
#include"PriorityQueue.hpp"
void Test()
{
int array[]={12,8,3,53,22,77,19,32};
PriorityQueue<int,Less<int>> q(array,sizeof(array)/sizeof(array[0]));
q.Push(9);
q.Pop();
}
int main()
{
Test();
return 0;
}