第19章 斐波那契堆
19.1 斐波那契堆結構
斐波那契堆是一系列具有最小堆序的有根樹的集合,棵樹都遵循最小堆性質。
相關的屬性:
1.
2.
3.
4.
5.
6.
7.
8.
9.
勢函數:
19.2 可合併堆操作
- 創建一個新的斐波那契堆
MAKE-FIB-HEAP()過程分配並返回一個斐波那契堆對象H,其中H..n=0,H.min=NIL 。實際代價爲O(1) 。 - 插入一個結點:
實際代價爲O(1) 。
FIB-HEAP-INSERT(H,x){
x.degree = 0
x.p = NIL
x.child = NIL
x.mark = FALSE
if H.min == NIL
create a root list for H containing just x
H.min = x
else
insert x into H's root list
if x.key < H.min.key
H.min = x
H.n++
}
- 尋找最小結點:
可以直接通過H.min得到,實際代價爲O(1) 。 - 兩個斐波那契堆的合併
實際代價爲O(1) 。
FIB-HEAT-UNIN(H1, H2){
H = MAKE-FIB-HEAP()
H.min = H1.min
concatenate the root list of H2 with the root list of H
if (H.min == NIL)||(H2.min != NIL && H2.min.key < H1.min.key)
H.min = H2.min
H.n = H1.n + H2.n
return H
}
- 抽取最小結點:
實際代價爲O(lgn) 。
FIB-HEAP-EXTRACT-MIN(H){
z = H.min
if z != NIL
for each child of z
add x to the root list of H
x.p = NIL
remove z from the root list of H
if z == z.right //z is the only one root of H
H.min = NIL
else
H.min = z.right
CONSOLIDATE(H)
H.n--
return z
}
//A[0..D(H.n)]記錄根結點對應的度數的軌跡,如果A[i]=y,則y是一個具有y.degree=i的根
CONSOLIDATE(H){
let A[0..D(H.n)] be a new array
for i=0 to D(H.n)
A[i]=NIL
for each node w in the root list of H
x = w
d = x.degree
while A[d] != NIL
y = A[d] //another node with the same dagree as x
if x.key > y.key
exchange x with y
FIB-HEAP-LINK(H,y,x)
A[d]=NIL
d++
A[d] = x
H.min = NIL
for i=0 to D(H.n)
if A[i] != NIL
if H.min == NIL
create a root list for H containing just A[i]
H.min = A[i]
else
insert A[i] into H's roott list
if A[i].key < H.min
H.min = A[i]
}
FIB-HEAP-LINK(H,y,x){
remove y from the root list of H
make y a child of x, increamentingg x.degree
y.mark = FALSE
}
19.3 關鍵字減值和刪除一個結點
- 關鍵字減值:
FIB-HEAP-DECREASE(H,x,k){
if k > x.key
error "new key is greater than current key"
x.key = k
y = x.p
if y != NIL && x.key < y.key
CUT(H,x,y)
CASCADING-CUT(H,y)
if x.key < H.min.key
H.min= x
}
CUT(H,y){
remove x from the child list of y, decrementing y.degree
add x to the root list of H
x.p = NIL
x.mark = FALSE
}
CASCADING-CUT(H,y){
z = y.p
if z != NIL
if y.mark == FALSE
y.mark = TRUE
else
CUT(H,y)
CASCADING-CUT(H,z)
}
- 刪除一個結點:
FIB-HEAP-DELECT(H,x){
FIB-HEAP-DECREASE(H,x,-inf)
FIB-HEAP-EXTRACT-MIN(H)
}