首页 > 代码库 > 堆(优先队列)模板
堆(优先队列)模板
包含向上、向下两种维护方向,方便手动维护堆中单个元素(STL的priority_queue和make_heap没有这种功能T_T)
namespace heap{
#define p(x) ((x) >> 1)
#define l(x) ((x) << 1)
#define r(x) (((x) << 1) + 1)
#define maxn ((int)1e5)
template <typename T>
struct heap{
T heap[maxn];
int size;
bool (*cmp)(T &a, T &b);
void swap(T &a,T &b){T t = a;a = b;b = t;}
bool Cmp(T &a, T &b){return a < b;}
heap(){size = 0;cmp = Cmp;}
heap(bool(*C)(T &a, T &b)){//参数为比较函数cmp的指针
size = 0;
cmp = C;
}
heap(T *begin, T *end){
size = end - begin;
int i = 0;
for(;i < size;++i)
heap[i+1] = *(begin + i);
for(i = size;i;--i)
maintainup(i);
}
void maintaindown(int k){
int M = k;
bool ctn;
while(l(k) < size){
ctn = 0;
if(cmp(heap[l(k)], heap[M]))M = l(k);
if(r(k) < size && cmp(heap[r(k)],heap[M]))M = r(k);
if(k != M)swap(M, k), ctn = 1, k = M;
if(!ctn)return;
}
}
void maintainup(int k){
while(p(k) && cmp(heap[k], heap[p(k)]))
swap(heap[k], heap[p(k)]), k = p(k);
}
void insert(int k){
heap[++size] = k;
maintainup(k);
}
void pop(int k){
heap[k] = heap[size--];
if(cmp(heap[p(k)],heap[k])maintaindown(k);
else maintainup(k);
}
};
}//namespce heap
#define p(x) ((x) >> 1)
#define l(x) ((x) << 1)
#define r(x) (((x) << 1) + 1)
#define maxn ((int)1e5)
template <typename T>
struct heap{
T heap[maxn];
int size;
bool (*cmp)(T &a, T &b);
void swap(T &a,T &b){T t = a;a = b;b = t;}
bool Cmp(T &a, T &b){return a < b;}
heap(){size = 0;cmp = Cmp;}
heap(bool(*C)(T &a, T &b)){//参数为比较函数cmp的指针
size = 0;
cmp = C;
}
heap(T *begin, T *end){
size = end - begin;
int i = 0;
for(;i < size;++i)
heap[i+1] = *(begin + i);
for(i = size;i;--i)
maintainup(i);
}
void maintaindown(int k){
int M = k;
bool ctn;
while(l(k) < size){
ctn = 0;
if(cmp(heap[l(k)], heap[M]))M = l(k);
if(r(k) < size && cmp(heap[r(k)],heap[M]))M = r(k);
if(k != M)swap(M, k), ctn = 1, k = M;
if(!ctn)return;
}
}
void maintainup(int k){
while(p(k) && cmp(heap[k], heap[p(k)]))
swap(heap[k], heap[p(k)]), k = p(k);
}
void insert(int k){
heap[++size] = k;
maintainup(k);
}
void pop(int k){
heap[k] = heap[size--];
if(cmp(heap[p(k)],heap[k])maintaindown(k);
else maintainup(k);
}
};
}//namespce heap
堆(优先队列)模板
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。