zoukankan      html  css  js  c++  java
  • 堆(优先队列)模板

    包含向上、向下两种维护方向,方便手动维护堆中单个元素(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
  • 相关阅读:
    多线程使用常识
    《30天自制操作系统》实现中文显示
    DDD实践(一)
    为了钱这是很正当的,我跟你干,我要获得一个好的收入,我要改善我的生活,我要提高我的生活质量(转)
    Java对象序列化/反序列化的注意事项(转)
    Java使用Socket传输文件遇到的问题(转)
    大胆采用开源工具(转)
    如果常量类进行改变时,只编译常量类,而使用常量的类不重新编码,这样改动实际上算没有生效(转)
    在html中写python代码的语法和特点-----基于webpy的httpserver
    在Activity中为什么要用managedQuery()
  • 原文地址:https://www.cnblogs.com/Asm-Definer/p/4008005.html
Copyright © 2011-2022 走看看