Compared with the binary heap, the implementation of the D-cross heap does not change much. First, let's see how it is represented by arrays.
Consider an array with an index starting from 1. A node I can have a maximum of D subnodes, ranging from ID-(D-2) to ID + 1.
The calculation method of the parent node of node I is as follows: (I + D-2)/d.
The second problem is the height of a D-cross heap containing n elements, which is a simple proportional sequence, we can know that the number of nodes contained in a full d Cross Tree with H is (d ^ (H + 1)-1)/(d-1)
Thus, a tree with N knots meets the following conditions:
To obtain the height h:
The implementation of the next three questions is similar to the pseudo code in the book. The source code is directly attached as follows:
# Include <iostream> # include <algorithm> using namespace STD; const int d = 5; # define parent (I) (I + D-2) /D # define child (k)-(D-2) + k-1 void max_heapify (int A [], int I, Int & size) {int largest = I; for (int K = 1; k <= D; k ++) {int child = I + child (k ); if (Child <= size & A [child]> A [Largest]) largest = Child;} If (largest! = I) {swap (A [I], a [Largest]); max_heapify (A, largest, size) ;}} int heap_extract_max (int A [], Int & size) {If (size <1) Return-1; int max = A [1]; A [1] = A [size]; size --; max_heapify (A, 1, size); Return Max;} void heap_increase_key (int A [], int I, int key) {If (Key <= A [I]) return; A [I] = key; while (I> 1 & A [Parent (I)] <A [I]) {swap (A [I], A [Parent (I)]); I = parent (I) ;}} void max_heap_insert (int A [], Int & size, int key) {size ++; A [size] = int_min; heap_increase_key (A, size, key );}
Chapter 6 Introduction to algorithms questions 6-3 D cross-Stack