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
  • 相关阅读:
    JAVA微信公众号网页开发——获取公众号关注的所有用户
    删除mysl
    sql语言(mysql)
    mycat读写分离
    mysql双主双从技术
    实用的10个日志处理案例
    ansible基本操作
    MySQL改密
    mysql源码包安装
    ftp搭建mysql服务器
  • 原文地址:https://www.cnblogs.com/Asm-Definer/p/4008005.html
Copyright © 2011-2022 走看看