Exemple #1
0
puzzle delete_heap (void)
{
   puzzle return_val;
   puzzle tmp;
   int favored_child;
   int index;

   if (heap_size == 0) {
      printf ("Heap underflow\n");
      exit (-1);
   }
   return_val = heap[0];
   heap[0] = heap[heap_size-1];
   heap_size--;
   index = 0;
   while (LCHILD(index) < heap_size) {
      if (RCHILD(index) >= heap_size) favored_child = LCHILD(index);
      else if (superior(RCHILD(index),LCHILD(index)))
         favored_child = RCHILD(index);
      else favored_child = LCHILD(index);
      if (superior(index, favored_child)) break;
      tmp = heap[index];
      heap[index] = heap[favored_child];
      heap[favored_child] = tmp;
      index = favored_child;
   }
   return return_val;
}
Exemple #2
0
void rem(MinHeap m, int value) {
    
    int index = findIndex(m, value);
    
    if (index < 0)
        return;
    
    int count = m->used - 1;
    m->used--;
    m->values[index] = m->values[count];
    
    while (LCHILD(index) < count && (m->values[index] > m->values[LCHILD(index)] ||
           m->values[index] > m->values[RCHILD(index)])) {
        if (m->values[LCHILD(index)] < m->values[RCHILD(index)]) {
            swap(m->values, LCHILD(index), index);
            index = LCHILD(index);
        }
        else {
            swap(m->values, RCHILD(index), index);
            index = RCHILD(index);            
        }
    }
    

    
}
Exemple #3
0
/*
    Function to display all the nodes in the min heap by doing a post order traversal
*/
void postorderTraversal(minHeap *hp, int i) {
    printf("%d ", hp->elem[i].data) ;
    if(LCHILD(i) < hp->size) {
        postorderTraversal(hp, LCHILD(i)) ;
    }
    if(RCHILD(i) < hp->size) {
        postorderTraversal(hp, RCHILD(i)) ;
    }
}
Exemple #4
0
/*
    Heapify function is used to make sure that the heap property is never violated
    In case of deletion of a node, or creating a min heap from an array, heap property
    may be violated. In such cases, heapify function can be called to make sure that
    heap property is never violated
*/
void heapify(minHeap *hp, int i) {
    int smallest = (LCHILD(i) < hp->size && hp->elem[LCHILD(i)].data < hp->elem[i].data) ? LCHILD(i) : i ;
    if(RCHILD(i) < hp->size && hp->elem[RCHILD(i)].data < hp->elem[smallest].data) {
        smallest = RCHILD(i) ;
    }
    if(smallest != i) {
        swap(&(hp->elem[i]), &(hp->elem[smallest])) ;
        heapify(hp, smallest) ;
    }
}
Exemple #5
0
void heapify(BinHeap *bh, int i){
    int smallest = (LCHILD(i) < bh->size && bh->A[LCHILD(i)].priority < bh->A[i].priority) ? LCHILD(i) : i ;
    if(RCHILD(i) < bh->size && bh->A[RCHILD(i)].priority < bh->A[smallest].priority) {
        smallest = RCHILD(i) ;
    }
    if(smallest != i) {
        swap(&(bh->A[i]), &(bh->A[smallest])) ;
        heapify(bh, smallest) ;
    }
}
Exemple #6
0
static void heapify(min_heap_t *mheap, int i)
{
    int smallest = (LCHILD(i) < mheap->cur_size && 
		mheap->buffer[LCHILD(i)] < mheap->buffer[i]) ? LCHILD(i) : i ;

    if(RCHILD(i) < mheap->cur_size && 
		mheap->buffer[RCHILD(i)] < mheap->buffer[smallest]) {
        smallest = RCHILD(i) ;
    }
    if(smallest != i) {
        swap(&(mheap->buffer[i]), &(mheap->buffer[smallest])) ;
        heapify(mheap, smallest) ;
    }	
}
Exemple #7
0
void heapify(Heap *heap, int node_index) {
  int smallest = node_index;

  if (LCHILD(node_index) < heap->current_size) {
    smallest = get_smaller_node(heap, LCHILD(node_index), smallest);
  }

  if (RCHILD(node_index) < heap->current_size) {
    smallest = get_smaller_node(heap, RCHILD(node_index), smallest);
  }

  if(smallest != node_index) {
    swap(&(heap->elem[node_index]), &(heap->elem[smallest]));
    heapify(heap, smallest);
  }
}
Exemple #8
0
// Fixes the heap after a timer has been deleted or modified.
__inline void TimerHeapHeapify(int index)
{
   int i = index;
   while (i > 0 && timer_heap[i]->time < timer_heap[PARENT(i)]->time)
   {
      TimerSwapIndex(i, PARENT(i));
      i = PARENT(i);
   }
   do
   {
      int min = i;
      if (LCHILD(i) < numActiveTimers && timer_heap[LCHILD(i)]->time <= timer_heap[min]->time)
         min = LCHILD(i);
      if (RCHILD(i) < numActiveTimers && timer_heap[RCHILD(i)]->time < timer_heap[min]->time)
         min = RCHILD(i);
      if (min == i)
         break;
      TimerSwapIndex(i, min);
      i = min;
   } while (true);
}
Exemple #9
0
 void downward(int cur){
     int left = LCHILD(cur);
     int right = RCHILD(cur);
     if (left < size){
         int min = left;
         if (right < size && arr[right] < arr[left]) min = right;
         if (arr[min] < arr[cur]){
             swap(min, cur);
             downward(min);
         }
     }
 }
Exemple #10
0
// Traverses the timer heap and returns false if the heap is invalid at any point.
bool TimerHeapCheck(int i, int level)
{
   if (i >= numActiveTimers)
      return true;

   if (LCHILD(i) < numActiveTimers && timer_heap[LCHILD(i)]->time < timer_heap[i]->time)
   {
      dprintf("TimerHeapCheck error on level %i", level);
      return false;
   }
   if (RCHILD(i) < numActiveTimers && timer_heap[RCHILD(i)]->time < timer_heap[i]->time)
   {
      dprintf("TimerHeapCheck error on level %i", level);
      return false;
   }

   bool retval = TimerHeapCheck(LCHILD(i), ++level);
   if (!retval)
      return false;

   return TimerHeapCheck(RCHILD(i), level);
}
static long long int get_val(struct node *nodes, int index) {
    struct node *current = nodes + index;
    if (current->start == current->end) {
        return current->offset;
    }

    int lindex = LCHILD(index);
    int rindex = RCHILD(index);

    long long int lval = get_val(nodes, lindex);
    long long int rval = get_val(nodes, rindex);

    return current->offset + (lval > rval ? lval : rval);
}
Exemple #12
0
/*
    Function to get maximum node from a min heap
    The maximum node shall always be one of the leaf nodes. So we shall recursively
    move through both left and right child, until we find their maximum nodes, and
    compare which is larger. It shall be done recursively until we get the maximum
    node
*/
int getMaxNode(minHeap *hp, int i) {
    if(LCHILD(i) >= hp->size) {
        return hp->elem[i].data ;
    }

    int l = getMaxNode(hp, LCHILD(i)) ;
    int r = getMaxNode(hp, RCHILD(i)) ;

    if(l >= r) {
        return l ;
    } else {
        return r ;
    }
}
// Enforce the heap property at root assuming the sub tree root at each child is a heap.
void heapify (Heap * heap, size_t root) {
	if (root >= heap->length / 2) { // Check if root is a leaf.
		return;
	}
	int * root_ptr = &heap->data[root];
	// smallest points to the smallest element from the root and its children. 
	int * smallest = (R(root) < heap->length) ? 
					 ptrMin(root_ptr, ptrMin(LCHILD(root), RCHILD(root))): // ptrMin return pointer to the smaller value.
					 ptrMin(root_ptr, LCHILD(root));
	if (smallest != root_ptr) {
		swap(smallest, root_ptr);
		smallest == LCHILD(root) ? heapify(heap, L(root)) : heapify(heap, R(root));
	}
}
/* prerequire: node has start and end set */
static void init_node(struct node *nodes, int index) {
    struct node *current = nodes + index;
    int start = current->start;
    int end   = current->end;
    int lindex = LCHILD(index);
    int rindex = RCHILD(index);
    struct node *left = nodes + lindex;
    struct node *right = nodes + rindex;

    left->start  = start;
    left->end    = start + (end - start + 1) / 2 - 1;
    right->start = start + (end - start + 1) / 2;
    right->end   = end;
    if (left->start < left->end) {
        init_node(nodes, lindex);
    }

    if (right->start < right->end) {
        init_node(nodes, rindex);
    }
}
static void feed(struct node *nodes, int index, int start, int end, int val) {
    struct node *current = nodes + index;
    /* printf("feed index: %d c: [%d, %d] f: [%d, %d]\n", index, current->start, current->end, start, end); */
    assert(current->start <= start);
    assert(current->end   >= end);

    if (current->start == start && current->end == end) {
        /* not propagate to childs */
        current->offset += val;
        /* current->val    += val; */
        /* child_updated(nodes, index); */
        return;
    }

    /* no child! */
    if (current->start == current->end) {
        current->offset += val;
        /* current->val += val; */
        /* child_updated(nodes, index); */
        return;
    }

    int lend = current->start + (current->end - current->start + 1) / 2 - 1;


    /* the left half */
    if (start <= lend) {
        int lindex = LCHILD(index);
        int cend = end >= lend ? lend : end;
        feed(nodes, lindex, start, cend, val);
    }

    /* the right half */
    if (end > lend) {
        int rindex = RCHILD(index);
        int cstart = start >= lend + 1 ? start : lend + 1;
        feed(nodes, rindex, cstart, end, val);
    }
}
Exemple #16
0
static void bufsort(void *base, size_t size, cmpfn compare CTXPARAM,
		    size_t start, size_t nmemb)
{
    size_t n, i;

    /*
     * Phase 1: build the heap. We want the _largest_ element at
     * the top.
     */
    n = 0;
    while (n < nmemb) {
	n++;

	/*
	 * Swap element n with its parent repeatedly to preserve
	 * the heap property.
	 */
	i = n-1;

	while (i > 0) {
	    int p = PARENT(i);

	    if (COMPARE(start+p, start+i) < 0) {
		SWAP(start+p, start+i);
		i = p;
	    } else
		break;
	}
    }

    /*
     * Phase 2: repeatedly remove the largest element and stick it
     * at the top of the array.
     */
    while (n > 0) {
	/*
	 * The largest element is at position 0. Put it at the top,
	 * and swap the arbitrary element from that position into
	 * position 0.
	 */
	n--;
	SWAP(start+0, start+n);

	/*
	 * Now repeatedly move that arbitrary element down the heap
	 * by swapping it with the more suitable of its children.
	 */
	i = 0;
	while (1) {
	    int lc, rc;

	    lc = LCHILD(i);
	    rc = RCHILD(i);

	    if (lc >= n)
		break;		       /* we've hit bottom */

	    if (rc >= n) {
		/*
		 * Special case: there is only one child to check.
		 */
		if (COMPARE(start+i, start+lc) < 0)
		    SWAP(start+i, start+lc);

		/* _Now_ we've hit bottom. */
		break;
	    } else {
		/*
		 * The common case: there are two children and we
		 * must check them both.
		 */
		if (COMPARE(start+i, start+lc) < 0 ||
		    COMPARE(start+i, start+rc) < 0) {
		    /*
		     * Pick the more appropriate child to swap with
		     * (i.e. the one which would want to be the
		     * parent if one were above the other - as one
		     * is about to be).
		     */
		    if (COMPARE(start+lc, start+rc) < 0) {
			SWAP(start+i, start+rc);
			i = rc;
		    } else {
			SWAP(start+i, start+lc);
			i = lc;
		    }
		} else {
		    /* This element is in the right place; we're done. */
		    break;
		}
	    }
	}
    }
}
Exemple #17
0
void maxflow_setup_backedges(int ne, const int *edges, int *backedges)
{
    int i, n;

    for (i = 0; i < ne; i++)
	backedges[i] = i;

    /*
     * We actually can't use the C qsort() function, because we'd
     * need to pass `edges' as a context parameter to its
     * comparator function. So instead I'm forced to implement my
     * own sorting algorithm internally, which is a pest. I'll use
     * heapsort, because I like it.
     */

#define LESS(i,j) ( (edges[2*(i)+1] < edges[2*(j)+1]) || \
		    (edges[2*(i)+1] == edges[2*(j)+1] && \
		     edges[2*(i)] < edges[2*(j)]) )
#define PARENT(n) ( ((n)-1)/2 )
#define LCHILD(n) ( 2*(n)+1 )
#define RCHILD(n) ( 2*(n)+2 )
#define SWAP(i,j) do { int swaptmp = (i); (i) = (j); (j) = swaptmp; } while (0)

    /*
     * Phase 1: build the heap. We want the _largest_ element at
     * the top.
     */
    n = 0;
    while (n < ne) {
	n++;

	/*
	 * Swap element n with its parent repeatedly to preserve
	 * the heap property.
	 */
	i = n-1;

	while (i > 0) {
	    int p = PARENT(i);

	    if (LESS(backedges[p], backedges[i])) {
		SWAP(backedges[p], backedges[i]);
		i = p;
	    } else
		break;
	}
    }

    /*
     * Phase 2: repeatedly remove the largest element and stick it
     * at the top of the array.
     */
    while (n > 0) {
	/*
	 * The largest element is at position 0. Put it at the top,
	 * and swap the arbitrary element from that position into
	 * position 0.
	 */
	n--;
	SWAP(backedges[0], backedges[n]);

	/*
	 * Now repeatedly move that arbitrary element down the heap
	 * by swapping it with the more suitable of its children.
	 */
	i = 0;
	while (1) {
	    int lc, rc;

	    lc = LCHILD(i);
	    rc = RCHILD(i);

	    if (lc >= n)
		break;		       /* we've hit bottom */

	    if (rc >= n) {
		/*
		 * Special case: there is only one child to check.
		 */
		if (LESS(backedges[i], backedges[lc]))
		    SWAP(backedges[i], backedges[lc]);

		/* _Now_ we've hit bottom. */
		break;
	    } else {
		/*
		 * The common case: there are two children and we
		 * must check them both.
		 */
		if (LESS(backedges[i], backedges[lc]) ||
		    LESS(backedges[i], backedges[rc])) {
		    /*
		     * Pick the more appropriate child to swap with
		     * (i.e. the one which would want to be the
		     * parent if one were above the other - as one
		     * is about to be).
		     */
		    if (LESS(backedges[lc], backedges[rc])) {
			SWAP(backedges[i], backedges[rc]);
			i = rc;
		    } else {
			SWAP(backedges[i], backedges[lc]);
			i = lc;
		    }
		} else {
		    /* This element is in the right place; we're done. */
		    break;
		}
	    }
	}
    }

#undef LESS
#undef PARENT
#undef LCHILD
#undef RCHILD
#undef SWAP

}
Exemple #18
0
/**************************************************************************************
 * Function:    CategorizeAndExpand
 *
 * Description: derive the quantizer setting for each region, based on decoded power
 *                envelope, number of bits available, and rateCode index
 *
 * Inputs:      pointer to initialized Gecko2Info struct
 *              number of bits remaining in bitstream for this frame
 *
 * Outputs:     catbuf[], which contains the correct quantizer index (cat) for each
 *                region, based on the rateCode read from bitstream
 *
 * Return:      none
 **************************************************************************************/
void CategorizeAndExpand(Gecko2Info *gi, int availbits)
{
	int r, n, k, val;
	int offset, delta, cat;
	int expbits, maxbits, minbits;
	int maxptr, minptr;
	int nminheap = 0, nmaxheap = 0;
	int *cp;
	int *maxcat = gi->db.maxcat;
	int *mincat = gi->db.mincat;
	int *changes = gi->db.changes;
	int *maxheap = gi->db.maxheap;
	int *minheap = gi->db.minheap;
	int *rmsIndex = gi->db.rmsIndex;
	int *catbuf = gi->db.catbuf;
	int rateCode = gi->rateCode;

	/* it's okay not to zero-init maxheap/minheap[1 ... MAXCREGN]
	 * we don't read maxheap/minheap[1+] without putting something in them first
	 */
	maxheap[0] = 0x7fffffff;	/* upheap sentinel */
	minheap[0] = 0x80000000;	/* upheap sentinel */

	/* Hack to compensate for different statistics at higher bits/sample */
	if (availbits > gi->nSamples)
		availbits = gi->nSamples + ((availbits - gi->nSamples) * 5/8);
	/*
	 * Initial categorization.
	 *
	 * This attempts to assigns categories to regions using
	 * a simple approximation of perceptual masking.
	 * Offset is chosen via binary search for desired bits.
	 */
	offset = -32;	/* start with minimum offset */
	for (delta = 32; delta > 0; delta >>= 1) {

		expbits = 0;
		for (r = 0; r < gi->cRegions; r++) {

			/* Test categorization at (offset+delta) */
			cat = (offset + delta - rmsIndex[r]) / 2;
			if (cat < 0) cat = 0;	/* clip */
			if (cat > 7) cat = 7;	/* clip */
			expbits += expbits_tab[cat];	/* tally expected bits */
		}
		/* Find largest offset such that (expbits >= availbits-32) */
		if (expbits >= availbits-32)	/* if still over budget, */
			offset += delta;			/* choose increased offset */
	}

	/* Use the selected categorization */
	expbits = 0;
	for (r = 0; r < gi->cRegions; r++) {
		cat = (offset - rmsIndex[r]) / 2;
		if (cat < 0) cat = 0;	/* clip */
		if (cat > 7) cat = 7;	/* clip */
		expbits += expbits_tab[cat];
		mincat[r] = cat;	/* init */
		maxcat[r] = cat;	/* init */

		val = offset - rmsIndex[r] - 2*cat;
		val = (val << 16) | r;	/* max favors high r, min favors low r */

		/* build maxheap */
		if (cat < 7) {
			/* insert at heap[N+1] */
			k = ++nmaxheap;
			maxheap[k] = val;
			/* upheap */
			while (val > maxheap[PARENT(k)]) {
				maxheap[k] = maxheap[PARENT(k)];
				k = PARENT(k);
			}
			maxheap[k] = val;
		}

		/* build minheap */
		if (cat > 0) {
			/* insert at heap[N+1] */
			k = ++nminheap;
			minheap[k] = val;
			/* upheap */
			while (val < minheap[PARENT(k)]) {
				minheap[k] = minheap[PARENT(k)];
				k = PARENT(k);
			}
			minheap[k] = val;
		}
	}

	/* init */
	minbits = expbits;
	maxbits = expbits;
	minptr = gi->nCatzns;	/* grows up, post-increment */
	maxptr = gi->nCatzns;	/* grows down, pre-decrement */

	/*
	 * Derive additional categorizations.
	 *
	 * Each new categorization differs from the last in a single region,
	 * where the categories differ by one, and are ordered by decreasing
	 * expected bits.
	 */
	for (n = 1; n < gi->nCatzns; n++) {
		/* Choose whether new cat should have larger/smaller bits */

		if (maxbits + minbits <= 2*availbits) {
			/* if average is low, add one with more bits */
			if (!nminheap) {
				/* printf("all quants at min\n"); */
				break;
			}
			r = minheap[1] & 0xffff;

			/* bump the chosen region */
			changes[--maxptr] = r;				/* add to change list */
			maxbits -= expbits_tab[maxcat[r]];	/* sub old bits */
			maxcat[r] -= 1;						/* dec category */
			maxbits += expbits_tab[maxcat[r]];	/* add new bits */

			/* update heap[1] */
			k = 1;
			if (maxcat[r] == 0)
				minheap[k] = minheap[nminheap--];	/* remove */
			else
				minheap[k] += (2 << 16);			/* update */

			/* downheap */
			val = minheap[k];
			while (k <= PARENT(nminheap)) {
				int child = LCHILD(k);
				int right = RCHILD(k);
				if ((right <= nminheap) && (minheap[right] < minheap[child]))
					child = right;
				if (val < minheap[child])
					break;
				minheap[k] = minheap[child];
				k = child;
			}
			minheap[k] = val;

		} else {
			/* average is high, add one with less bits */
			if (!nmaxheap) {
				/* printf("all quants at max\n"); */
				break;
			}
			r = maxheap[1] & 0xffff;

			/* bump the chosen region */
			changes[minptr++] = r;				/* add to change list */
			minbits -= expbits_tab[mincat[r]];	/* sub old bits */
			mincat[r] += 1;						/* inc category */
			minbits += expbits_tab[mincat[r]];	/* add new bits */

			/* update heap[1] */
			k = 1;
			if (mincat[r] == 7)
				maxheap[k] = maxheap[nmaxheap--];	/* remove */
			else
				maxheap[k] -= (2 << 16);			/* update */

			/* downheap */
			val = maxheap[k];
			while (k <= PARENT(nmaxheap)) {
				int child = LCHILD(k);
				int right = RCHILD(k);
				if ((right <= nmaxheap) && (maxheap[right] > maxheap[child]))
					child = right;
				if (val > maxheap[child])
					break;
				maxheap[k] = maxheap[child];
				k = child;
			}
			maxheap[k] = val;
		}
	}

	/* largest categorization */
	for (r = 0; r < gi->cRegions; r++)
		catbuf[r] = maxcat[r];

	/* make sure rateCode is not greater than number of changes in list */
	ASSERT(rateCode <= (minptr - maxptr));

	/* expand categories using change list, starting at max cat
     * we change one region at a time (cat++ = coarser quantizer)
	 */
	cp = &changes[maxptr];
	while (rateCode--)
		catbuf[*cp++] += 1;

}