原文: https://www.programiz.com/dsa/fibonacci-heap

在本教程中,您将学习什么是斐波那契堆。 此外,您还将在 C,C++ ,Java 和 Python 中找到斐波纳契堆上不同操作的工作示例。

斐波那契堆是二项式堆的一种修改形式,其堆操作比二项式和二叉堆所支持的更有效。

与二叉堆不同,一个节点可以有两个以上的子节点。

斐波那契堆称为斐波那契堆,因为树的构建方式使得n阶树中至少有F n+2个节点,其中F n+2(n + 2)nd斐波那契数。

斐波那契堆 - 图1

斐波那契堆


斐波那契堆的性质

斐波那契堆的重要属性是:

  1. 它是最小堆有序树的集合。 (即,父级总是比子级小。)
  2. 指针保持在最小元素节点上。
  3. 它由一组标记的节点组成。 (减少按键操作)
  4. 斐波那契堆中的树是无序的,但植根于

斐波那契堆中节点的内存表示

所有树的根链接在一起,以加快访问速度。 父节点的子节点通过圆形双向链表相互连接,如下所示。

使用循环双链表有两个主要优点。

  1. 从树中删除节点需要O(1)时间。
  2. 两个这样的列表的连接需要花费O(1)时间。

斐波那契堆 - 图2

斐波那契堆结构


斐波那契堆上的操作

插入

算法

  1. insert(H, x)
  2. degree[x] = 0
  3. p[x] = NIL
  4. child[x] = NIL
  5. left[x] = x
  6. right[x] = x
  7. mark[x] = FALSE
  8. concatenate the root list containing x with root list H
  9. if min[H] == NIL or key[x] < key[min[H]]
  10. then min[H] = x
  11. n[H] = n[H] + 1

将节点插入到现有堆中的步骤如下。

  1. 为该元素创建一个新节点。
  2. 检查堆是否为空。
  3. 如果堆为空,则将新节点设置为根节点,并将其标记为min
  4. 否则,将节点插入根列表并更新min

斐波那契堆 - 图3

插入示例

寻找最小值

最小元素始终由min指针指定。

合并

两个斐波那契堆的并集包括以下步骤。

  1. 连接两个堆的根。
  2. 通过从新的根列表中选择一个最小键来更新min

斐波那契堆 - 图4

两个堆的组合

提取最小值

这是斐波那契堆上最重要的操作。 在此操作中,从堆中删除了具有最小值的节点,并重新调整了树。

遵循以下步骤:

  1. 删除最小节点。
  2. 将最小指针设置为根列表中的下一个根。
  3. 创建一个大小等于删除前堆中树的最大程度的数组。
  4. 执行以下操作(步骤 5-7),直到不存在具有相同度数的多个根。
  5. 将当前根的度数(最小指针)映射到数组中的度数。
  6. 将下一个根的度数映射到数组中的度数。
  7. 如果同一度数有两个以上的映射,则对这些根应用联合操作,以保持最小堆属性(即最小值在根处)。

在以下示例中可以理解上述步骤的实现。

  1. 我们将在下面的堆上执行extract-min操作。
    斐波那契堆 - 图5
    斐波那契堆

  2. 删除min节点,将其所有子节点添加到根列表中,并将min指针设置为根列表中的下一个根。
    斐波那契堆 - 图6
    删除最小节点

  3. 树中的最大度为 3。创建一个大小为 4 的数组,并使用该数组映射下一个根的度。
    斐波那契堆 - 图7
    创建数组

  4. 在这里,23 和 7 具有相同的度数,因此将它们合并。
    斐波那契堆 - 图8
    合并那些具有相同度数的人

  5. 同样,7 和 17 具有相同的度数,因此也将它们合并。
    斐波那契堆 - 图9
    合并那些具有相同度数的人

  6. 同样,7 和 24 具有相同的度数,因此将它们合并。
    斐波那契堆 - 图10
    合并那些具有相同度数的人

  7. 映射下一个节点。
    斐波那契堆 - 图11
    映射其余节点

  8. 同样,52 和 21 具有相同的度数,因此将它们合并
    斐波那契堆 - 图12
    将具有相同度数的合并

  9. 同样,将 21 和 18 组合在一起。
    斐波那契堆 - 图13
    将具有相同度数的那些组合在一起

  10. 映射剩余的根。

  1. ![Map the remaining nodes](https://cdn.nlark.com/yuque/0/2020/png/348784/1599989629528-1969319b-84f4-49af-90ec-7ca68daa8a9a.png "Extract min operation")
  2. 映射其余节点
  1. 最后的堆是。
  1. ![Final heap](https://cdn.nlark.com/yuque/0/2020/png/348784/1599989629568-33e2bb73-e55d-4a24-9f37-353275091afd.png "Extract min operation")
  2. 最终斐波那契堆

减少键并删除节点

这些是减少键和删除节点操作中讨论的最重要的操作。


Python,Java 和 C/C++ 示例

  1. # Fibonacci Heap in python
  2. import math
  3. # Creating fibonacci tree
  4. class FibonacciTree:
  5. def __init__(self, value):
  6. self.value = value
  7. self.child = []
  8. self.order = 0
  9. # Adding tree at the end of the tree
  10. def add_at_end(self, t):
  11. self.child.append(t)
  12. self.order = self.order + 1
  13. # Creating Fibonacci heap
  14. class FibonacciHeap:
  15. def __init__(self):
  16. self.trees = []
  17. self.least = None
  18. self.count = 0
  19. # Insert a node
  20. def insert_node(self, value):
  21. new_tree = FibonacciTree(value)
  22. self.trees.append(new_tree)
  23. if (self.least is None or value < self.least.value):
  24. self.least = new_tree
  25. self.count = self.count + 1
  26. # Get minimum value
  27. def get_min(self):
  28. if self.least is None:
  29. return None
  30. return self.least.value
  31. # Extract the minimum value
  32. def extract_min(self):
  33. smallest = self.least
  34. if smallest is not None:
  35. for child in smallest.child:
  36. self.trees.append(child)
  37. self.trees.remove(smallest)
  38. if self.trees == []:
  39. self.least = None
  40. else:
  41. self.least = self.trees[0]
  42. self.consolidate()
  43. self.count = self.count - 1
  44. return smallest.value
  45. # Consolidate the tree
  46. def consolidate(self):
  47. aux = (floor_log(self.count) + 1) * [None]
  48. while self.trees != []:
  49. x = self.trees[0]
  50. order = x.order
  51. self.trees.remove(x)
  52. while aux[order] is not None:
  53. y = aux[order]
  54. if x.value > y.value:
  55. x, y = y, x
  56. x.add_at_end(y)
  57. aux[order] = None
  58. order = order + 1
  59. aux[order] = x
  60. self.least = None
  61. for k in aux:
  62. if k is not None:
  63. self.trees.append(k)
  64. if (self.least is None
  65. or k.value < self.least.value):
  66. self.least = k
  67. def floor_log(x):
  68. return math.frexp(x)[1] - 1
  69. fibonacci_heap = FibonacciHeap()
  70. fibonacci_heap.insert_node(7)
  71. fibonacci_heap.insert_node(3)
  72. fibonacci_heap.insert_node(17)
  73. fibonacci_heap.insert_node(24)
  74. print('the minimum value of the fibonacci heap: {}'.format(fibonacci_heap.get_min()))
  75. print('the minimum value removed: {}'.format(fibonacci_heap.extract_min()))
  1. // Operations on Fibonacci Heap in Java
  2. // Node creation
  3. class node {
  4. node parent;
  5. node left;
  6. node right;
  7. node child;
  8. int degree;
  9. boolean mark;
  10. int key;
  11. public node() {
  12. this.degree = 0;
  13. this.mark = false;
  14. this.parent = null;
  15. this.left = this;
  16. this.right = this;
  17. this.child = null;
  18. this.key = Integer.MAX_VALUE;
  19. }
  20. node(int x) {
  21. this();
  22. this.key = x;
  23. }
  24. void set_parent(node x) {
  25. this.parent = x;
  26. }
  27. node get_parent() {
  28. return this.parent;
  29. }
  30. void set_left(node x) {
  31. this.left = x;
  32. }
  33. node get_left() {
  34. return this.left;
  35. }
  36. void set_right(node x) {
  37. this.right = x;
  38. }
  39. node get_right() {
  40. return this.right;
  41. }
  42. void set_child(node x) {
  43. this.child = x;
  44. }
  45. node get_child() {
  46. return this.child;
  47. }
  48. void set_degree(int x) {
  49. this.degree = x;
  50. }
  51. int get_degree() {
  52. return this.degree;
  53. }
  54. void set_mark(boolean m) {
  55. this.mark = m;
  56. }
  57. boolean get_mark() {
  58. return this.mark;
  59. }
  60. void set_key(int x) {
  61. this.key = x;
  62. }
  63. int get_key() {
  64. return this.key;
  65. }
  66. }
  67. public class fibHeap {
  68. node min;
  69. int n;
  70. boolean trace;
  71. node found;
  72. public boolean get_trace() {
  73. return trace;
  74. }
  75. public void set_trace(boolean t) {
  76. this.trace = t;
  77. }
  78. public static fibHeap create_heap() {
  79. return new fibHeap();
  80. }
  81. fibHeap() {
  82. min = null;
  83. n = 0;
  84. trace = false;
  85. }
  86. private void insert(node x) {
  87. if (min == null) {
  88. min = x;
  89. x.set_left(min);
  90. x.set_right(min);
  91. } else {
  92. x.set_right(min);
  93. x.set_left(min.get_left());
  94. min.get_left().set_right(x);
  95. min.set_left(x);
  96. if (x.get_key() < min.get_key())
  97. min = x;
  98. }
  99. n += 1;
  100. }
  101. public void insert(int key) {
  102. insert(new node(key));
  103. }
  104. public void display() {
  105. display(min);
  106. System.out.println();
  107. }
  108. private void display(node c) {
  109. System.out.print("(");
  110. if (c == null) {
  111. System.out.print(")");
  112. return;
  113. } else {
  114. node temp = c;
  115. do {
  116. System.out.print(temp.get_key());
  117. node k = temp.get_child();
  118. display(k);
  119. System.out.print("->");
  120. temp = temp.get_right();
  121. } while (temp != c);
  122. System.out.print(")");
  123. }
  124. }
  125. public static void merge_heap(fibHeap H1, fibHeap H2, fibHeap H3) {
  126. H3.min = H1.min;
  127. if (H1.min != null && H2.min != null) {
  128. node t1 = H1.min.get_left();
  129. node t2 = H2.min.get_left();
  130. H1.min.set_left(t2);
  131. t1.set_right(H2.min);
  132. H2.min.set_left(t1);
  133. t2.set_right(H1.min);
  134. }
  135. if (H1.min == null || (H2.min != null && H2.min.get_key() < H1.min.get_key()))
  136. H3.min = H2.min;
  137. H3.n = H1.n + H2.n;
  138. }
  139. public int find_min() {
  140. return this.min.get_key();
  141. }
  142. private void display_node(node z) {
  143. System.out.println("right: " + ((z.get_right() == null) ? "-1" : z.get_right().get_key()));
  144. System.out.println("left: " + ((z.get_left() == null) ? "-1" : z.get_left().get_key()));
  145. System.out.println("child: " + ((z.get_child() == null) ? "-1" : z.get_child().get_key()));
  146. System.out.println("degree " + z.get_degree());
  147. }
  148. public int extract_min() {
  149. node z = this.min;
  150. if (z != null) {
  151. node c = z.get_child();
  152. node k = c, p;
  153. if (c != null) {
  154. do {
  155. p = c.get_right();
  156. insert(c);
  157. c.set_parent(null);
  158. c = p;
  159. } while (c != null && c != k);
  160. }
  161. z.get_left().set_right(z.get_right());
  162. z.get_right().set_left(z.get_left());
  163. z.set_child(null);
  164. if (z == z.get_right())
  165. this.min = null;
  166. else {
  167. this.min = z.get_right();
  168. this.consolidate();
  169. }
  170. this.n -= 1;
  171. return z.get_key();
  172. }
  173. return Integer.MAX_VALUE;
  174. }
  175. public void consolidate() {
  176. double phi = (1 + Math.sqrt(5)) / 2;
  177. int Dofn = (int) (Math.log(this.n) / Math.log(phi));
  178. node[] A = new node[Dofn + 1];
  179. for (int i = 0; i <= Dofn; ++i)
  180. A[i] = null;
  181. node w = min;
  182. if (w != null) {
  183. node check = min;
  184. do {
  185. node x = w;
  186. int d = x.get_degree();
  187. while (A[d] != null) {
  188. node y = A[d];
  189. if (x.get_key() > y.get_key()) {
  190. node temp = x;
  191. x = y;
  192. y = temp;
  193. w = x;
  194. }
  195. fib_heap_link(y, x);
  196. check = x;
  197. A[d] = null;
  198. d += 1;
  199. }
  200. A[d] = x;
  201. w = w.get_right();
  202. } while (w != null && w != check);
  203. this.min = null;
  204. for (int i = 0; i <= Dofn; ++i) {
  205. if (A[i] != null) {
  206. insert(A[i]);
  207. }
  208. }
  209. }
  210. }
  211. // Linking operation
  212. private void fib_heap_link(node y, node x) {
  213. y.get_left().set_right(y.get_right());
  214. y.get_right().set_left(y.get_left());
  215. node p = x.get_child();
  216. if (p == null) {
  217. y.set_right(y);
  218. y.set_left(y);
  219. } else {
  220. y.set_right(p);
  221. y.set_left(p.get_left());
  222. p.get_left().set_right(y);
  223. p.set_left(y);
  224. }
  225. y.set_parent(x);
  226. x.set_child(y);
  227. x.set_degree(x.get_degree() + 1);
  228. y.set_mark(false);
  229. }
  230. // Search operation
  231. private void find(int key, node c) {
  232. if (found != null || c == null)
  233. return;
  234. else {
  235. node temp = c;
  236. do {
  237. if (key == temp.get_key())
  238. found = temp;
  239. else {
  240. node k = temp.get_child();
  241. find(key, k);
  242. temp = temp.get_right();
  243. }
  244. } while (temp != c && found == null);
  245. }
  246. }
  247. public node find(int k) {
  248. found = null;
  249. find(k, this.min);
  250. return found;
  251. }
  252. public void decrease_key(int key, int nval) {
  253. node x = find(key);
  254. decrease_key(x, nval);
  255. }
  256. // Decrease key operation
  257. private void decrease_key(node x, int k) {
  258. if (k > x.get_key())
  259. return;
  260. x.set_key(k);
  261. node y = x.get_parent();
  262. if (y != null && x.get_key() < y.get_key()) {
  263. cut(x, y);
  264. cascading_cut(y);
  265. }
  266. if (x.get_key() < min.get_key())
  267. min = x;
  268. }
  269. // Cut operation
  270. private void cut(node x, node y) {
  271. x.get_right().set_left(x.get_left());
  272. x.get_left().set_right(x.get_right());
  273. y.set_degree(y.get_degree() - 1);
  274. x.set_right(null);
  275. x.set_left(null);
  276. insert(x);
  277. x.set_parent(null);
  278. x.set_mark(false);
  279. }
  280. private void cascading_cut(node y) {
  281. node z = y.get_parent();
  282. if (z != null) {
  283. if (y.get_mark() == false)
  284. y.set_mark(true);
  285. else {
  286. cut(y, z);
  287. cascading_cut(z);
  288. }
  289. }
  290. }
  291. // Delete operations
  292. public void delete(node x) {
  293. decrease_key(x, Integer.MIN_VALUE);
  294. int p = extract_min();
  295. }
  296. public static void main(String[] args) {
  297. fibHeap obj = create_heap();
  298. obj.insert(7);
  299. obj.insert(26);
  300. obj.insert(30);
  301. obj.insert(39);
  302. obj.insert(10);
  303. obj.display();
  304. System.out.println(obj.extract_min());
  305. obj.display();
  306. System.out.println(obj.extract_min());
  307. obj.display();
  308. System.out.println(obj.extract_min());
  309. obj.display();
  310. System.out.println(obj.extract_min());
  311. obj.display();
  312. System.out.println(obj.extract_min());
  313. obj.display();
  314. }
  315. }
// Operations on a Fibonacci heap in C

#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct _NODE {
  int key;
  int degree;
  struct _NODE *left_sibling;
  struct _NODE *right_sibling;
  struct _NODE *parent;
  struct _NODE *child;
  bool mark;
  bool visited;
} NODE;

typedef struct fibanocci_heap {
  int n;
  NODE *min;
  int phi;
  int degree;
} FIB_HEAP;

FIB_HEAP *make_fib_heap();
void insertion(FIB_HEAP *H, NODE *new, int val);
NODE *extract_min(FIB_HEAP *H);
void consolidate(FIB_HEAP *H);
void fib_heap_link(FIB_HEAP *H, NODE *y, NODE *x);
NODE *find_min_node(FIB_HEAP *H);
void decrease_key(FIB_HEAP *H, NODE *node, int key);
void cut(FIB_HEAP *H, NODE *node_to_be_decrease, NODE *parent_node);
void cascading_cut(FIB_HEAP *H, NODE *parent_node);
void Delete_Node(FIB_HEAP *H, int dec_key);

FIB_HEAP *make_fib_heap() {
  FIB_HEAP *H;
  H = (FIB_HEAP *)malloc(sizeof(FIB_HEAP));
  H->n = 0;
  H->min = NULL;
  H->phi = 0;
  H->degree = 0;
  return H;
}

// Printing the heap
void print_heap(NODE *n) {
  NODE *x;
  for (x = n;; x = x->right_sibling) {
    if (x->child == NULL) {
      printf("node with no child (%d) \n", x->key);
    } else {
      printf("NODE(%d) with child (%d)\n", x->key, x->child->key);
      print_heap(x->child);
    }
    if (x->right_sibling == n) {
      break;
    }
  }
}

// Inserting nodes
void insertion(FIB_HEAP *H, NODE *new, int val) {
  new = (NODE *)malloc(sizeof(NODE));
  new->key = val;
  new->degree = 0;
  new->mark = false;
  new->parent = NULL;
  new->child = NULL;
  new->visited = false;
  new->left_sibling = new;
  new->right_sibling = new;
  if (H->min == NULL) {
    H->min = new;
  } else {
    H->min->left_sibling->right_sibling = new;
    new->right_sibling = H->min;
    new->left_sibling = H->min->left_sibling;
    H->min->left_sibling = new;
    if (new->key < H->min->key) {
      H->min = new;
    }
  }
  (H->n)++;
}

// Find min node
NODE *find_min_node(FIB_HEAP *H) {
  if (H == NULL) {
    printf(" \n Fibonacci heap not yet created \n");
    return NULL;
  } else
    return H->min;
}

// Union operation
FIB_HEAP *unionHeap(FIB_HEAP *H1, FIB_HEAP *H2) {
  FIB_HEAP *Hnew;
  Hnew = make_fib_heap();
  Hnew->min = H1->min;

  NODE *temp1, *temp2;
  temp1 = Hnew->min->right_sibling;
  temp2 = H2->min->left_sibling;

  Hnew->min->right_sibling->left_sibling = H2->min->left_sibling;
  Hnew->min->right_sibling = H2->min;
  H2->min->left_sibling = Hnew->min;
  temp2->right_sibling = temp1;

  if ((H1->min == NULL) || (H2->min != NULL && H2->min->key < H1->min->key))
    Hnew->min = H2->min;
  Hnew->n = H1->n + H2->n;
  return Hnew;
}

// Calculate the degree
int cal_degree(int n) {
  int count = 0;
  while (n > 0) {
    n = n / 2;
    count++;
  }
  return count;
}

// Consolidate function
void consolidate(FIB_HEAP *H) {
  int degree, i, d;
  degree = cal_degree(H->n);
  NODE *A[degree], *x, *y, *z;
  for (i = 0; i <= degree; i++) {
    A[i] = NULL;
  }
  x = H->min;
  do {
    d = x->degree;
    while (A[d] != NULL) {
      y = A[d];
      if (x->key > y->key) {
        NODE *exchange_help;
        exchange_help = x;
        x = y;
        y = exchange_help;
      }
      if (y == H->min)
        H->min = x;
      fib_heap_link(H, y, x);
      if (y->right_sibling == x)
        H->min = x;
      A[d] = NULL;
      d++;
    }
    A[d] = x;
    x = x->right_sibling;
  } while (x != H->min);

  H->min = NULL;
  for (i = 0; i < degree; i++) {
    if (A[i] != NULL) {
      A[i]->left_sibling = A[i];
      A[i]->right_sibling = A[i];
      if (H->min == NULL) {
        H->min = A[i];
      } else {
        H->min->left_sibling->right_sibling = A[i];
        A[i]->right_sibling = H->min;
        A[i]->left_sibling = H->min->left_sibling;
        H->min->left_sibling = A[i];
        if (A[i]->key < H->min->key) {
          H->min = A[i];
        }
      }
      if (H->min == NULL) {
        H->min = A[i];
      } else if (A[i]->key < H->min->key) {
        H->min = A[i];
      }
    }
  }
}

// Linking
void fib_heap_link(FIB_HEAP *H, NODE *y, NODE *x) {
  y->right_sibling->left_sibling = y->left_sibling;
  y->left_sibling->right_sibling = y->right_sibling;

  if (x->right_sibling == x)
    H->min = x;

  y->left_sibling = y;
  y->right_sibling = y;
  y->parent = x;

  if (x->child == NULL) {
    x->child = y;
  }
  y->right_sibling = x->child;
  y->left_sibling = x->child->left_sibling;
  x->child->left_sibling->right_sibling = y;
  x->child->left_sibling = y;
  if ((y->key) < (x->child->key))
    x->child = y;

  (x->degree)++;
}

// Extract min
NODE *extract_min(FIB_HEAP *H) {
  if (H->min == NULL)
    printf("\n The heap is empty");
  else {
    NODE *temp = H->min;
    NODE *pntr;
    pntr = temp;
    NODE *x = NULL;
    if (temp->child != NULL) {
      x = temp->child;
      do {
        pntr = x->right_sibling;
        (H->min->left_sibling)->right_sibling = x;
        x->right_sibling = H->min;
        x->left_sibling = H->min->left_sibling;
        H->min->left_sibling = x;
        if (x->key < H->min->key)
          H->min = x;
        x->parent = NULL;
        x = pntr;
      } while (pntr != temp->child);
    }

    (temp->left_sibling)->right_sibling = temp->right_sibling;
    (temp->right_sibling)->left_sibling = temp->left_sibling;
    H->min = temp->right_sibling;

    if (temp == temp->right_sibling && temp->child == NULL)
      H->min = NULL;
    else {
      H->min = temp->right_sibling;
      consolidate(H);
    }
    H->n = H->n - 1;
    return temp;
  }
  return H->min;
}

void cut(FIB_HEAP *H, NODE *node_to_be_decrease, NODE *parent_node) {
  NODE *temp_parent_check;

  if (node_to_be_decrease == node_to_be_decrease->right_sibling)
    parent_node->child = NULL;

  node_to_be_decrease->left_sibling->right_sibling = node_to_be_decrease->right_sibling;
  node_to_be_decrease->right_sibling->left_sibling = node_to_be_decrease->left_sibling;
  if (node_to_be_decrease == parent_node->child)
    parent_node->child = node_to_be_decrease->right_sibling;
  (parent_node->degree)--;

  node_to_be_decrease->left_sibling = node_to_be_decrease;
  node_to_be_decrease->right_sibling = node_to_be_decrease;
  H->min->left_sibling->right_sibling = node_to_be_decrease;
  node_to_be_decrease->right_sibling = H->min;
  node_to_be_decrease->left_sibling = H->min->left_sibling;
  H->min->left_sibling = node_to_be_decrease;

  node_to_be_decrease->parent = NULL;
  node_to_be_decrease->mark = false;
}

void cascading_cut(FIB_HEAP *H, NODE *parent_node) {
  NODE *aux;
  aux = parent_node->parent;
  if (aux != NULL) {
    if (parent_node->mark == false) {
      parent_node->mark = true;
    } else {
      cut(H, parent_node, aux);
      cascading_cut(H, aux);
    }
  }
}

void decrease_key(FIB_HEAP *H, NODE *node_to_be_decrease, int new_key) {
  NODE *parent_node;
  if (H == NULL) {
    printf("\n FIbonacci heap not created ");
    return;
  }
  if (node_to_be_decrease == NULL) {
    printf("Node is not in the heap");
  }

  else {
    if (node_to_be_decrease->key < new_key) {
      printf("\n Invalid new key for decrease key operation \n ");
    } else {
      node_to_be_decrease->key = new_key;
      parent_node = node_to_be_decrease->parent;
      if ((parent_node != NULL) && (node_to_be_decrease->key < parent_node->key)) {
        printf("\n cut called");
        cut(H, node_to_be_decrease, parent_node);
        printf("\n cascading cut called");
        cascading_cut(H, parent_node);
      }
      if (node_to_be_decrease->key < H->min->key) {
        H->min = node_to_be_decrease;
      }
    }
  }
}

void *find_node(FIB_HEAP *H, NODE *n, int key, int new_key) {
  NODE *find_use = n;
  NODE *f = NULL;
  find_use->visited = true;
  if (find_use->key == key) {
    find_use->visited = false;
    f = find_use;
    decrease_key(H, f, new_key);
  }
  if (find_use->child != NULL) {
    find_node(H, find_use->child, key, new_key);
  }
  if ((find_use->right_sibling->visited != true)) {
    find_node(H, find_use->right_sibling, key, new_key);
  }

  find_use->visited = false;
}

FIB_HEAP *insertion_procedure() {
  FIB_HEAP *temp;
  int no_of_nodes, ele, i;
  NODE *new_node;
  temp = (FIB_HEAP *)malloc(sizeof(FIB_HEAP));
  temp = NULL;
  if (temp == NULL) {
    temp = make_fib_heap();
  }
  printf(" \n enter number of nodes to be insert = ");
  scanf("%d", &no_of_nodes);
  for (i = 1; i <= no_of_nodes; i++) {
    printf("\n node %d and its key value = ", i);
    scanf("%d", &ele);
    insertion(temp, new_node, ele);
  }
  return temp;
}
void Delete_Node(FIB_HEAP *H, int dec_key) {
  NODE *p = NULL;
  find_node(H, H->min, dec_key, -5000);
  p = extract_min(H);
  if (p != NULL)
    printf("\n Node deleted");
  else
    printf("\n Node not deleted:some error");
}

int main(int argc, char **argv) {
  NODE *new_node, *min_node, *extracted_min, *node_to_be_decrease, *find_use;
  FIB_HEAP *heap, *h1, *h2;
  int operation_no, new_key, dec_key, ele, i, no_of_nodes;
  heap = (FIB_HEAP *)malloc(sizeof(FIB_HEAP));
  heap = NULL;
  while (1) {
    printf(" \n Operations \n 1\. Create Fibonacci heap \n 2\. Insert nodes into fibonacci heap \n 3\. Find min \n 4\. Union \n 5\. Extract min \n 6\. Decrease key \n 7.Delete node \n 8\. print heap \n 9\. exit \n enter operation_no = ");
    scanf("%d", &operation_no);

    switch (operation_no) {
      case 1:
        heap = make_fib_heap();
        break;

      case 2:
        if (heap == NULL) {
          heap = make_fib_heap();
        }
        printf(" enter number of nodes to be insert = ");
        scanf("%d", &no_of_nodes);
        for (i = 1; i <= no_of_nodes; i++) {
          printf("\n node %d and its key value = ", i);
          scanf("%d", &ele);
          insertion(heap, new_node, ele);
        }
        break;

      case 3:
        min_node = find_min_node(heap);
        if (min_node == NULL)
          printf("No minimum value");
        else
          printf("\n min value = %d", min_node->key);
        break;

      case 4:
        if (heap == NULL) {
          printf("\n no FIbonacci heap created \n ");
          break;
        }
        h1 = insertion_procedure();
        heap = unionHeap(heap, h1);
        printf("Unified Heap:\n");
        print_heap(heap->min);
        break;

      case 5:
        if (heap == NULL)
          printf("Empty Fibonacci heap");
        else {
          extracted_min = extract_min(heap);
          printf("\n min value = %d", extracted_min->key);
          printf("\n Updated heap: \n");
          print_heap(heap->min);
        }
        break;

      case 6:
        if (heap == NULL)
          printf("Fibonacci heap is empty");
        else {
          printf(" \n node to be decreased = ");
          scanf("%d", &dec_key);
          printf(" \n enter the new key = ");
          scanf("%d", &new_key);
          find_use = heap->min;
          find_node(heap, find_use, dec_key, new_key);
          printf("\n Key decreased- Corresponding heap:\n");
          print_heap(heap->min);
        }
        break;
      case 7:
        if (heap == NULL)
          printf("Fibonacci heap is empty");
        else {
          printf(" \n Enter node key to be deleted = ");
          scanf("%d", &dec_key);
          Delete_Node(heap, dec_key);
          printf("\n Node Deleted- Corresponding heap:\n");
          print_heap(heap->min);
          break;
        }
      case 8:
        print_heap(heap->min);
        break;

      case 9:
        free(new_node);
        free(heap);
        exit(0);

      default:
        printf("Invalid choice ");
    }
  }
}
// Operations on a Fibonacci heap in C++

#include <cmath>
#include <cstdlib>
#include <iostream>

using namespace std;

// Node creation
struct node {
  int n;
  int degree;
  node *parent;
  node *child;
  node *left;
  node *right;
  char mark;

  char C;
};

// Implementation of Fibonacci heap
class FibonacciHeap {
   private:
  int nH;

  node *H;

   public:
  node *InitializeHeap();
  int Fibonnaci_link(node *, node *, node *);
  node *Create_node(int);
  node *Insert(node *, node *);
  node *Union(node *, node *);
  node *Extract_Min(node *);
  int Consolidate(node *);
  int Display(node *);
  node *Find(node *, int);
  int Decrease_key(node *, int, int);
  int Delete_key(node *, int);
  int Cut(node *, node *, node *);
  int Cascase_cut(node *, node *);
  FibonacciHeap() { H = InitializeHeap(); }
};

// Initialize heap
node *FibonacciHeap::InitializeHeap() {
  node *np;
  np = NULL;
  return np;
}

// Create node
node *FibonacciHeap::Create_node(int value) {
  node *x = new node;
  x->n = value;
  return x;
}

// Insert node
node *FibonacciHeap::Insert(node *H, node *x) {
  x->degree = 0;
  x->parent = NULL;
  x->child = NULL;
  x->left = x;
  x->right = x;
  x->mark = 'F';
  x->C = 'N';
  if (H != NULL) {
    (H->left)->right = x;
    x->right = H;
    x->left = H->left;
    H->left = x;
    if (x->n < H->n)
      H = x;
  } else {
    H = x;
  }
  nH = nH + 1;
  return H;
}

// Create linking
int FibonacciHeap::Fibonnaci_link(node *H1, node *y, node *z) {
  (y->left)->right = y->right;
  (y->right)->left = y->left;
  if (z->right == z)
    H1 = z;
  y->left = y;
  y->right = y;
  y->parent = z;

  if (z->child == NULL)
    z->child = y;

  y->right = z->child;
  y->left = (z->child)->left;
  ((z->child)->left)->right = y;
  (z->child)->left = y;

  if (y->n < (z->child)->n)
    z->child = y;
  z->degree++;
}

// Union Operation
node *FibonacciHeap::Union(node *H1, node *H2) {
  node *np;
  node *H = InitializeHeap();
  H = H1;
  (H->left)->right = H2;
  (H2->left)->right = H;
  np = H->left;
  H->left = H2->left;
  H2->left = np;
  return H;
}

// Display the heap
int FibonacciHeap::Display(node *H) {
  node *p = H;
  if (p == NULL) {
    cout << "Empty Heap" << endl;
    return 0;
  }
  cout << "Root Nodes: " << endl;

  do {
    cout << p->n;
    p = p->right;
    if (p != H) {
      cout << "-->";
    }
  } while (p != H && p->right != NULL);
  cout << endl;
}

// Extract min
node *FibonacciHeap::Extract_Min(node *H1) {
  node *p;
  node *ptr;
  node *z = H1;
  p = z;
  ptr = z;
  if (z == NULL)
    return z;

  node *x;
  node *np;

  x = NULL;

  if (z->child != NULL)
    x = z->child;

  if (x != NULL) {
    ptr = x;
    do {
      np = x->right;
      (H1->left)->right = x;
      x->right = H1;
      x->left = H1->left;
      H1->left = x;
      if (x->n < H1->n)
        H1 = x;

      x->parent = NULL;
      x = np;
    } while (np != ptr);
  }

  (z->left)->right = z->right;
  (z->right)->left = z->left;
  H1 = z->right;

  if (z == z->right && z->child == NULL)
    H = NULL;

  else {
    H1 = z->right;
    Consolidate(H1);
  }
  nH = nH - 1;
  return p;
}

// Consolidation Function
int FibonacciHeap::Consolidate(node *H1) {
  int d, i;
  float f = (log(nH)) / (log(2));
  int D = f;
  node *A[D];

  for (i = 0; i <= D; i++)
    A[i] = NULL;

  node *x = H1;
  node *y;
  node *np;
  node *pt = x;

  do {
    pt = pt->right;

    d = x->degree;

    while (A[d] != NULL)

    {
      y = A[d];

      if (x->n > y->n)

      {
        np = x;

        x = y;

        y = np;
      }

      if (y == H1)
        H1 = x;
      Fibonnaci_link(H1, y, x);
      if (x->right == x)
        H1 = x;
      A[d] = NULL;
      d = d + 1;
    }

    A[d] = x;
    x = x->right;

  }

  while (x != H1);
  H = NULL;
  for (int j = 0; j <= D; j++) {
    if (A[j] != NULL) {
      A[j]->left = A[j];
      A[j]->right = A[j];
      if (H != NULL) {
        (H->left)->right = A[j];
        A[j]->right = H;
        A[j]->left = H->left;
        H->left = A[j];
        if (A[j]->n < H->n)
          H = A[j];
      } else {
        H = A[j];
      }
      if (H == NULL)
        H = A[j];
      else if (A[j]->n < H->n)
        H = A[j];
    }
  }
}

// Decrease Key Operation
int FibonacciHeap::Decrease_key(node *H1, int x, int k) {
  node *y;
  if (H1 == NULL) {
    cout << "The Heap is Empty" << endl;
    return 0;
  }
  node *ptr = Find(H1, x);
  if (ptr == NULL) {
    cout << "Node not found in the Heap" << endl;
    return 1;
  }

  if (ptr->n < k) {
    cout << "Entered key greater than current key" << endl;
    return 0;
  }
  ptr->n = k;
  y = ptr->parent;
  if (y != NULL && ptr->n < y->n) {
    Cut(H1, ptr, y);
    Cascase_cut(H1, y);
  }

  if (ptr->n < H->n)
    H = ptr;

  return 0;
}

// Cutting Function
int FibonacciHeap::Cut(node *H1, node *x, node *y)

{
  if (x == x->right)
    y->child = NULL;
  (x->left)->right = x->right;
  (x->right)->left = x->left;
  if (x == y->child)
    y->child = x->right;
  y->degree = y->degree - 1;
  x->right = x;
  x->left = x;
  (H1->left)->right = x;
  x->right = H1;
  x->left = H1->left;
  H1->left = x;
  x->parent = NULL;
  x->mark = 'F';
}

// Cascade cut
int FibonacciHeap::Cascase_cut(node *H1, node *y) {
  node *z = y->parent;
  if (z != NULL) {
    if (y->mark == 'F') {
      y->mark = 'T';
    } else

    {
      Cut(H1, y, z);
      Cascase_cut(H1, z);
    }
  }
}

// Search function
node *FibonacciHeap::Find(node *H, int k) {
  node *x = H;
  x->C = 'Y';
  node *p = NULL;
  if (x->n == k) {
    p = x;
    x->C = 'N';
    return p;
  }

  if (p == NULL) {
    if (x->child != NULL)
      p = Find(x->child, k);
    if ((x->right)->C != 'Y')
      p = Find(x->right, k);
  }

  x->C = 'N';
  return p;
}

// Deleting key
int FibonacciHeap::Delete_key(node *H1, int k) {
  node *np = NULL;
  int t;
  t = Decrease_key(H1, k, -5000);
  if (!t)
    np = Extract_Min(H);
  if (np != NULL)
    cout << "Key Deleted" << endl;
  else
    cout << "Key not Deleted" << endl;
  return 0;
}

int main() {
  int n, m, l;
  FibonacciHeap fh;
  node *p;
  node *H;
  H = fh.InitializeHeap();

  p = fh.Create_node(7);
  H = fh.Insert(H, p);
  p = fh.Create_node(3);
  H = fh.Insert(H, p);
  p = fh.Create_node(17);
  H = fh.Insert(H, p);
  p = fh.Create_node(24);
  H = fh.Insert(H, p);

  fh.Display(H);

  p = fh.Extract_Min(H);
  if (p != NULL)
    cout << "The node with minimum key: " << p->n << endl;
  else
    cout << "Heap is empty" << endl;

  m = 26;
  l = 16;
  fh.Decrease_key(H, m, l);

  m = 16;
  fh.Delete_key(H, m);
}

复杂度

插入 O(1)
寻找最小值 O(1)
合并 O(1)
提取最小值 O(log n)
减小键 O(1)
删除节点 O(log n)

斐波那契堆应用

  1. 为了提高 Dijkstra 算法的渐近运行时间。