push_heap算法 (即满足max-heap条件,最大值在根节点)
生活随笔
收集整理的這篇文章主要介紹了
push_heap算法 (即满足max-heap条件,最大值在根节点)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
算法描述
完全二叉樹,父節點值比子節點大。(不保證左節點值大于右節點值。)
?
新元素插入時要滿足的條件
為了滿足完全二叉樹的條件,新加入的元素一定要放在最下一層作為葉節點,并填補在由左至右的第一個空格,也就是把新元素插入在底層vector的end()處。
?
用到的技巧
這里有一個小技巧,如果用array存儲所有節點,并且將array的#0位置的元素保留(即下標從1開始),那么當完全二叉樹的某個節點位移array的i處時,其左節點必位于array的2i處,其右節點必位于array的2i+1處,其父節點必位于”i/2”處(i/2取整)。用array實現完全二叉樹的方式稱為隱式表述法(implicit representation)。
?
SGI? STL? push_heap算法實現
SGI STL計算父節點與左右節點的方式與上面的技巧略有不同,但原理類似(可以認為SGI中下標從1開始)。
算法核心:
// 以下這組 push_back()不允許指定「大小比較標準」 template <class RandomAccessIterator, class Distance, class T> void __push_heap(RandomAccessIterator first, Distance holeIndex,Distance topIndex, T value) {Distance parent = (holeIndex - 1) / 2; // 找出父節點while (holeIndex > topIndex && *(first + parent) < value) {// 當尚未到達頂端,且父節點小於新值(於是不符合 heap 的次序特性)// 由於以上使用 operator<,可知 STL heap 是一種 max-heap(大者為父)。*(first + holeIndex) = *(first + parent); // 令洞值為父值holeIndex = parent; // percolate up:調整洞號,向上提昇至父節點。parent = (holeIndex - 1) / 2; // 新洞的父節點} // 持續至頂端,或滿足 heap 的次序特性為止。*(first + holeIndex) = value; // 令洞值為新值,完成安插動作。 }?
?接口函數:?template <class RandomAccessIterator, class Compare> inline void push_heap(RandomAccessIterator first, RandomAccessIterator last,Compare comp) {__push_heap_aux(first, last, comp, distance_type(first), value_type(first)); } template <class RandomAccessIterator, class Compare, class Distance, class T> inline void __push_heap_aux(RandomAccessIterator first,RandomAccessIterator last, Compare comp,Distance*, T*) {__push_heap(first, Distance((last - first) - 1), Distance(0), T(*(last - 1)), comp); }轉載于:https://www.cnblogs.com/helloweworld/archive/2013/01/05/2845528.html
總結
以上是生活随笔為你收集整理的push_heap算法 (即满足max-heap条件,最大值在根节点)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 心得14-hibernate的优化2-抓
- 下一篇: html5开发windows8应用 wi