『數據結構』斐波那契堆 1. 結構 2. 勢函數 3. 最大度數 4. 操作 最大度數的證明

1. 結構

斐波那契堆是一系列具有最小堆序的有根樹的集合, 同一代(層)結點由雙向循環鏈表鏈接, 爲了便於刪除最小結點, 還需要維持鏈表爲升序, 即nd<=nd.right(nd==nd.right時只有一個結點或爲 None), 父子之間都有指向對方的指針.

結點有degree 屬性, 記錄孩子的個數, mark 屬性用來標記(爲了滿足勢函數, 達到攤還需求的)

還有一個最小值指針 H.min 指向最小根結點


2. 勢函數

下面用勢函數來分析攤還代價, 如果你不明白, 可以看攤還分析

\Phi(H) = t(H) + 2m(h)
t 是根鏈表中樹的數目,m(H) 表示被標記的結點數

最初沒有結點

3. 最大度數

結點的最大度數(即孩子數)D(n)\leqslant \lfloor lgn \rfloor, 證明放在最後

4. 操作

4.1. 創建一個斐波那契堆

O(1)

4.2. 插入一個結點

nd = new node
nd.prt = nd.chd = None
if H.min is None:
    creat H with nd
    H.min = nd
else:
    insert nd into  H's root list
    if H.min<nd: H.min = nd
H.n +=1

\Delta \Phi = \Delta t(H) + 2\Delta m(H) = 1+0 = 1
攤還代價爲O(1)

4.3. 尋找最小結點

直接用 H.min, O(1)

4.4. 合併兩個斐波那契堆

def union(H1,H2):
    if H1.min ==None or (H1.min and H2.min and H1.min>H2.min):
        H1.min = H2.min
    link H2.rootList to H1.rootList 
    return H1

易知 \Delta \Phi = 0

4.5. 抽取最小值

抽取最小值, 一定是在根結點, 然後將此根結點的所有子樹的根放在 根結點雙向循環鏈表中, 之後還要進行樹的合併. 以使每個根結點的度不同,

def extract-min(H):
    z = H.min
    if z!=None:
        for chd of z:
            link chd to H.rootList
            chd.prt = None
        remove z from the rootList of H
        if z==z.right:
            H.min = None
        else:
            H.min = z.right
            consolidate(H)
        H.n -=1
    return z

consolidate 函數使用一個 輔助數組degree來記錄所有根結點(不超過lgn)對應的度數, degree[i] = nd 表示.有且只有一個結點 nd 的度數爲 i.

def consolidate(H):
    initialize degree  with None
    for nd in H.rootList:
        d = nd.degree
        while degree[d] !=None:
            nd2 = degree[d]
            if nd2.degree < nd.degree:
                nd2,nd = nd,nd2

            make nd2 child of nd  
            nd.degree = d+1
            nd.mark = False # to balace the potential 

            remove nd2 from H.rootList
            degree[d] = None
            d+=1
        else: degree[d] = nd
    for i in degree:
        if i!=None: 
            link i to H.rootList
            if H.min ==None: H.min = i
            else if H.min>i: H.min = i

時間複雜度爲O(lgn) 即數組移動的長度, 而最多有 lgn個元素

4.6. 關鍵字減值

def decrease-key(H,x,k):
    if k>x.key: error 
    x.key = k
    y=x.p
    if y!=None and x.key < y.key:
        cut(H,x,y)
        cascading-cut(H,y)
    if x.key < H.min.key:
      H.min = x
def cut(H,x,y):
    remove x from the child list of y, decrementing y.degree
    add x to H.rootList
    x.prt = None
     x.mark = False

def cascading-cut(H,y):
    z- y,prt
    if z !=None:
        if y.mark ==False:y.mark = True
        else:
            cut(H,y,z)
            cascading-cut(H,z)

4.7. 刪除結點

decrease(H,nd, MIN)
extract-min(H)

最大度數的證明

這也是斐波那契這個名字的由來,
D(n)\leqslant \lfloor lgn \rfloor

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章