assass_cannotin的超级二叉堆模板

二叉堆模板

大家可能不是很喜欢或者不会手写堆,又觉得priority_queue太慢,那怎么办呢
复制粘贴assass_cannotin的万能二叉堆模板是你膜你赛水题的最佳选择
这个堆的操作没有做太多,一时没有想到,希望大家可以在下面提建议
<代码过丑,速度较慢什么的大家还是放过我吧>
上代码

template <class T,int max_size,bool compare(const T &a,const T &b)>class Heap
{
private:
  T heap[max_size];
  int heap_size;
  inline void swap(T &a,T &b)
  {
    T temp=a;
    a=b,b=temp;
  }
  void up(int now)
  {
    if(now==1)return ;
    int nxxt=now>>1;
    T temp=heap[now];
    while(compare(temp,heap[nxxt])&&now>1)
    {
        heap[now]=heap[nxxt];
        now=nxxt,nxxt>>=1;
    }
    heap[now]=temp;
  }
  void down(int now)
  {
    int nxxt=now<<1;
    T temp=heap[now];
    while(nxxt<=heap_size)
    {
        if(nxxt<heap_size&&compare(heap[nxxt+1],heap[nxxt]))
        nxxt++;
        if(compare(temp,heap[nxxt]))break;
        else
        {
            heap[now]=heap[nxxt];
            now=nxxt,nxxt<<=1;
        }
    }
    heap[now]=temp;
  }
public:
  Heap()
  {
    heap_size=0;
  }
  inline void push(T a)
  {
      heap[++heap_size]=a;
      up(heap_size);
  }
  inline void pop()
  {
    heap[1]=heap[heap_size--];
    down(1);
  }
  inline T top(){return heap[1];}
  inline T pop_out()
  {
    T temp=heap[1];
    heap[1]=heap[heap_size--];
    down(1);
    return temp;
  }
  inline void clear(){heap_size=0;}
  inline bool empty(){return !heap_size;}
  inline int size(){return heap_size;}
};

push是插入操作
pop是弹出堆顶
pop_out是返回堆顶并弹出
top是访问堆顶元素
max_size是最多能容纳几个元素(可能这个就是为什么比stl快的原因)
clear是(伪)清空堆内元素,不清空内存
assass_cannotin的堆不支持运算符,也就是不管是什么类型,都要使用cmp函数
但我觉得这样更好更方便
注:
1.cmp函数的第一个参数优先级更高
2.这个堆一开始就是空的,不用clear
3.什么类型都可以,什么node,shit都可以
下面是使用样例,一个int类型,元素上限是10000009的小根堆

inline bool cmp(const int &a,const int &b){return a<b;}
Heap<int,1000010,cmp>heap;

很妙很妙
具体效率优势
这里写图片描述
下面是assass_cannotin的堆模板
上面的是priority_queue
蒟蒻太弱了,先跑了
2018.3.19更新
这里写图片描述
改为递归版

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值