日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

树形结构:优先级队列,堆

發布時間:2024/9/15 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 树形结构:优先级队列,堆 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

優先級隊列,堆是比較常用的數據結構,分支限界法,貪心法均會用到優先級隊列

有必要了解一下優先級隊列的實現方式

# -*- 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]

總結

以上是生活随笔為你收集整理的树形结构:优先级队列,堆的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。