zoukankan      html  css  js  c++  java
  • stl_heap

    学习一下stl_heap 

             下面的算法是根据stl源码重新整合一下,是为了方便理解

             因为使用的迭代器,为了在给定的迭代器之间使用heap的一些方法,

             内部通常用disHole来确定某个节点 dishole 是指与first距离,可取0 1 2 3 4.....

    inline void push_heap(int heap[], int first, int last)
    {
        //disHole 指 当前结点 到first的距离 因此距离 是从 0 1 2 3 .....
        int disHole = (last - first) - 1;
        int disHoleParent = (disHole - 1) / 2;
        int value = heap[first+disHole];
        while (disHole> 0 && heap[first + disHoleParent] < value)
        {
            heap[first+disHole] = heap[first+disHoleParent];
            disHole = disHoleParent;
            disHoleParent = (disHole - 1) / 2;
        }
        heap[first + disHole] = value;
    }
    
    //调用此方法时 实际上将 最顶 元素 放到了最后
    //从上往下调整
    inline void pop_heap(int heap[], int first, int last)
    {
        int value = heap[last - 1];
        heap[last - 1] = heap[first];
        int disHole = first-first;
    
        int disSecondHoleChild = (disHole * 2 + 2);
        while (disSecondHoleChild < (last - first - 1))
        {
            if (heap[first + disSecondHoleChild] < heap[first + disSecondHoleChild - 1])
                disSecondHoleChild--;
            heap[first+disHole] = heap[first+disSecondHoleChild];
            disHole = disSecondHoleChild;
            disSecondHoleChild = (disHole * 2 + 2);
        }
        if (disSecondHoleChild == (last - first - 1))
        {
            heap[first + disHole] = heap[first + disSecondHoleChild - 1];
            disHole = disSecondHoleChild - 1;
        }
    
        heap[first+disHole] = value;
    //这一步,因为在while 循环中,并没有设置让当前大于子女节点时退时
    //所以插入后,使用push_head 进行向上调整
    //当然暂时不理解stl在设计时 为何在while中不进行判断 break push_heap(heap, first, disHole
    + 1); } //利用pop_heap 原理实现 排序 inline void sort_heap(int heap[],int first,int last) { while((last-first)>1) { pop_heap(heap, first, last--); } } //make_heap 将其调整为最大堆 inline void make_heap(int heap[],int first,int last) { if ((last - first) < 2)return; int dislen = last - first - 1; int disParent = (dislen - 1) / 2; while(true) { push_heap(heap, first, first + disParent + 1); if(disParent==0)return; disParent--; } }
  • 相关阅读:
    BestCoder Round #71 (div.2) (hdu 5621)
    BestCoder Round #71 (div.2) (hdu 5620 菲波那切数列变形)
    BestCoder Round #69 (div.2) Baby Ming and Weight lifting(hdu 5610)
    BestCoder Round #70 Jam's math problem(hdu 5615)
    BestCoder Round #68 (div.2) tree(hdu 5606)
    poj 2299 Ultra-QuickSort(归并排序或是bit 树+离散化皆可)
    hdu 3874 Necklace(bit树+事先对查询区间右端点排序)
    HDU 4300 Clairewd’s message(KMP)
    HDU 3308 LCIS(线段树单点更新区间合并)
    PKU 3667 Hotel(线段树)
  • 原文地址:https://www.cnblogs.com/infoo/p/7603659.html
Copyright © 2011-2022 走看看