void Consolidate (struct heap* H){ //O(log n) int Dn = (int)floor(log10(H->n - 1)/log10(2)); int i; struct node** A = (struct node**)malloc(Dn*sizeof(struct node*)); for (i=0; i<=Dn; i++){ A[i] = NULL; } struct node* w = H->min; struct node* tmp = NULL; struct node* x = NULL; struct node* y = NULL; struct node* buf = NULL; int d, num = 0, k = 0; if (H->min){ num++; while (w != H->min->left){ num++; buf = w->right; w = buf; } } w = H->min; for (; k < num; k++){ x = w; d = x->degree; while (A[d]){ y = A[d]; if (x->key > y->key){ buf = x; x = y; y = buf; } Fib_Heap_Link(H, y, x); A[d] = NULL; d++; } A[d] = x; tmp = x->right; w = tmp; } H->min = NULL; for (i=0; i<=Dn; i++){ if (A[i]){ if ((H->min == NULL) || (A[i]->key < H->min->key)) { H->min = A[i]; //H->min->left->right = A[i]; //êàæåòñÿ, è áåç ýòîãî ðàáîòàåò //A[i]->left = H->min->left; //A[i]->right = H->min; //H->min->left = A[i]; } } } }
void fibonacci_heap::Consolidate() { //int golden_ratio = static_cast<int>(floor(log(static_cast<double>(n))/log(static_cast<double>(1 + sqrt(static_cast<double>(5)))/2))); int max_degree = (int)floor(log((double)n)/log(GOLDEN_RATIO)); int d_hn = max_degree+2; //for good measure. // let A[O .. D(H.n)] be a new array Node** A = new Node*[d_hn]; // for i = 0 to D(H.n) for (int i = 0; i < d_hn; i++) A[i] = nullptr; // A[i] = NIL // create a root list to iterate int rootSize = 0; Node* next; Node* w = min; do { next = w->right; rootSize++; w = next; } while (w != min); Node** rootList = new Node*[rootSize]; for (int i=0; i < rootSize; i++) { rootList[i] = next; next = next->right; } // for each node w in the root list of H //Node* w = min; for (int i=0; i < rootSize; i++) { // x = w Node* x = rootList[i]; // d = x.degree int d = x->degree; // while A[d] != NIL while ( A[d] != nullptr ) { Node* y = A[d]; // another node with same degree as x if ( x->key > y->key ) { // exchange x with y Node* temp = x; x = y; y = temp; } Fib_Heap_Link(y,x); A[d] = nullptr; d++; } A[d] = x; } delete [] rootList; min = nullptr; // for i = 0 to D(H.n) for (int i=0; i < d_hn; i++) { if (A[i] != nullptr) { if (min == nullptr) { min = A[i]; // create a root list for H containing just A[i] min->right = min; min->left = min; } else { // insert A[i] into H's root list min->left->right = A[i]; A[i]->left = min->left; min->left = A[i]; A[i]->right = min; // update min element if (A[i]->key < min->key) min = A[i]; } } } delete [] A; }