堆(优先队列)模板

包含向上、向下两种维护方向,方便手动维护堆中单个元素(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

 

posted @ 2014-10-06 10:40  Asm.Definer  阅读(194)  评论(0编辑  收藏  举报