树形结构:优先级队列,堆
生活随笔
收集整理的這篇文章主要介紹了
树形结构:优先级队列,堆
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
優先級隊列,堆是比較常用的數據結構,分支限界法,貪心法均會用到優先級隊列
有必要了解一下優先級隊列的實現方式
# -*- coding: utf-8 -*-# 最大堆# 很顯然這是一個雙針模型,指著一對父子,父親小于兒子,則兒子上位 def siftUp(arr,insert_index,insert_value):child_pointer = insert_indexparent_pointer = (child_pointer-1)//2pivot = insert_value#兒子不斷的挑戰父親while parent_pointer >=0 and arr[parent_pointer] < pivot:arr[child_pointer] = arr[parent_pointer]child_pointer = parent_pointerparent_pointer = (child_pointer-1)//2arr[child_pointer] = pivotdef siftDown(arr,insert_index,insert_value):end_index = len(arr)-1# 下沉也是雙針模型,父親每次和兒子里面最大的交換,逐步下沉parent_pointer = insert_indexchild_pointer = 2*parent_pointer + 1pivot = insert_valuewhile child_pointer <= end_index:# child_pointer指針總是指向兒子里面最大的那個if child_pointer + 1 <= end_index and arr[child_pointer + 1] >arr[child_pointer]:child_pointer +=1# 假如父親還是大于兩個兒子,就沒必要執行下沉操作if pivot >= arr[child_pointer]:break# 否則的話,和最大的兒子交換,逐步下沉,下沉時逐步更新父子指針else:arr[parent_pointer] = arr[child_pointer]parent_pointer = child_pointerchild_pointer = 2*parent_pointer + 1# 把最后空出來的位置進去 ,最后肯定parent_pointer為空,child_pointer越界 arr[parent_pointer] = pivot# 上浮構造的時候,就需要從頭到尾上浮,每個元素浮一遍 def buildHeapBySiftUp(arr):for i in range(len(arr)):siftUp(arr,i,arr[i]) # 下沉構造時,需要從尾到頭構造,每個元素沉一遍,實際上至多需要沉一半,因為后面一半 # 元素都是葉子 def buildHeapBySiftDown(arr):for i in range((len(arr)-1)//2 -1,-1,-1):siftDown(arr,i,arr[i])代碼測試
arr =[1,2,3,4,5,6] buildHeapBySiftUp(arr) print(arr) siftDown(arr,0,0) print(arr) arr3=[0,1,2,3,4,5,6] print(arr3) buildHeapBySiftDown(arr3) print(arr3)runfile('D:/share/test/heapqueue.py', wdir='D:/share/test') [6, 4, 5, 1, 3, 2] [5, 4, 2, 1, 3, 0] [0, 1, 2, 3, 4, 5, 6] [6, 4, 5, 3, 1, 0, 2]總結
以上是生活随笔為你收集整理的树形结构:优先级队列,堆的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 树形结构:使用栈实现,快排,先序遍历,归
- 下一篇: 树形结构:寻找共同祖先