コード例 #1
0
// Clean up Queue!
PriorityQueue::~PriorityQueue() {
    // head
    void* item = removeMin();
    while(item != 0x0){
        delete item;
        item = removeMin();
    }
}
コード例 #2
0
ファイル: k-way.c プロジェクト: marianstefi20/K-Way-Merge
int main() {
    // declarare lista vida
    Element **array;
    int nrListe, j, sumElemente = 0;
	
    printf("Cate liste vrei?");
    scanf("%d", &nrListe);
    array = create_array(nrListe, &sumElemente);
    // Afisare liste
    for(j=0;j<nrListe;j++) {
		printf("\n Lista [%d]\n", j);
		Afisare(array[j]);
	}
    printf("\n");
    
    
    // Definim un nou heap in care vom tine toate elementele
    struct heapStruct *h;
    h = initHeap();
    // Testam adaugarea primelor elemente din fiecare lista
    for(j=0;j<nrListe;j++) 
		insert(h, array[j]->valoare, j);
    printHeap(h);
	
	// Incepem sa punem primul element de pe heap primul
	int *result;
	result = (int*)malloc(sizeof(int)*sumElemente);
	int c = 0;
	printf("Marimea la heap: %d", nrListe);
	printf("Cate elemente vom avea: %d", sumElemente);
	while( nrListe > 0) {         
		heapElement min;
		int i, k;
		min = removeMin(h);
		i = min.list_index;
		k = min.value;
		printf("\n [Valoare|index] = [%d|%d]\n", k, i);
		nrListe--;
		// Trebuie sa stergem nodul cu indexul i
		StergereElement(&array[i]);
		
		
		result[c++] = k;
		if (array[i] != NULL && c < 100)  {
			insert(h, array[i]->valoare, i);         
			nrListe++;
		}
	}
	
	int i;
	printf("\n");
	for(i=0;i<sumElemente;i++) 
		printf("%d  ", result[i]);
	printf("\n");
	
	// In absenta lui free apareau anumite erori interesante
    free(array);

    return 0;
}
コード例 #3
0
int main() {

    int i;
    int vals[10];
    struct heapStruct *h;
    h = initHeap();

    // Insert from input stream.
    h = readIn(h);
    // print it
    printHeap(h);

    // Delete some and print delete and new heap
    for (i=0; i<9; i++) {
        printf("Delete %d\n",removeMin(h));
        printHeap(h);
    }
    freeHeap(h);

    // Test out array initialization.
    vals[0] = 12, vals[1] = 3, vals[2] = 18, vals[3] = 14, vals[4] = 5;
    vals[5] = 9, vals[6] = 1, vals[7] = 7; vals[8] = 2, vals[9] = 13;

    sort(vals, 10);

    for (i=0; i<10; i++)
        printf("%d ", vals[i]);
    printf("\n");

    system("echo \"done\"");
    return 0;
}
コード例 #4
0
void huffman(void)
{ struct CForest min1, min2;
  while (treeCnt > 1) {
    /* Намиране и премахване на двата най-леки върха */
    min1 = forest[1];
    removeMin();
    min2 = forest[1];
    removeMin();
    /* Създаване на нов възел - обединение на двата най-редки */
    forest[++treeCnt].root = (struct tree *) malloc(sizeof(struct tree));
    forest[treeCnt].root->left = min1.root;
    forest[treeCnt].root->right = min2.root;
    forest[treeCnt].weight = min1.weight + min2.weight;
    /* Вмъкване на възела */
    siftUp(treeCnt);
  }
}
コード例 #5
0
// Runs a heap sort by creating a heap out of the values in the array, and then
// extracting those values one-by-one from the heap back into the array in the
// proper order.
void sort(int values[], int length) {
     struct heapStruct *h;
     int i;

     // Create a heap from the array of values.
     h =  initHeapfromArray(values, length);
     length = h->size;

     // Remove these values from the heap one by one and store them back in the
     // original array.
     for (i=0; i<length; i++) values[i] = removeMin(h);
}
コード例 #6
0
void Graph<T>::minSpanTreeSimple(bool print)
{
	std::vector<EdgeNode<T>*> minSpanTree;					//to store all the edges in minimum spanning tree.
	int totalCost =0;							//stores total cost of minimum spanning tree
	if(graph != NULL && !graph->empty())
	{
		typename std::map<T,VertexNode<T>*>::iterator iter = graph->begin();
		std::map<T,bool> visitedMap;
		for(;iter!=graph->end();++iter)
		{
			VertexNode<T>* vertex = iter->second;
			visitedMap[vertex->getVertex()]=false;
		}
		iter = graph-> begin();
		VertexNode<T>* currVertex = iter->second;				//selecting first node in map.
		while(minSpanTree.size() != graph->size()-1)	//Iterate till all the vertex are included in MST.
		{
			if(currVertex!=NULL && !visitedMap[currVertex->getVertex()])
			{
				//Code for adding all edges for CurrentVertex in edgeList and also getting the minimum in same iteration.
				EdgeNode<T>* temp = currVertex->edgeListHead;		//head for the edgeList
				while(temp != NULL)
				{
				//storing the edge on vector.
					if(!visitedMap[temp->getDestination()->getVertex()])	//if(!(temp->getDestination()->isVisited()))
					{
						insert(temp);
					}
					temp = temp->next;
				}
				//Set visited for the current Vertex
				visitedMap[currVertex->getVertex()]= true;
			}

			//Find minimum of edgeList and remove it from the list.
			EdgeNode<T>* minEdge = removeMin();
			//Add minEdge to MST with current vertex to destination vertex.
			minSpanTree.push_back(minEdge);
			totalCost = totalCost + minEdge->getCost();
			currVertex = minEdge->getDestination();
		}
	}
	if(print)
	{
		cout<<totalCost<<endl;
		typename std::vector<EdgeNode<T>*>::iterator iter = minSpanTree.begin();
		for(;iter!=minSpanTree.end();++iter)
			cout<<(*iter)->getSource()->getVertex()<<" "<<(*iter)->getDestination()->getVertex()<<endl;
	}
}
コード例 #7
0
ファイル: testMinMaxHeap.c プロジェクト: yannakisg/g-clibrary
int main() {
	MinMaxHeap heap;
	
	initMinMaxHeap(&heap, NULL, DEFAULTSIZE, THRESHOLD);
	
	srand(time(NULL));
	
	int sorted[SIZE],array[SIZE];
	int i;
	
	for (i = 0; i < SIZE; i++) {
		array[i] = (rand() % UPPERSIZE) + 1;
		mmHeapPut(&heap,array[i], &array[i]);
	}
	
	traverseHeap(&heap);
	
	int *min, *max;
	
	getMin(&heap, (void **)&min);
	getMax(&heap, (void **)&max);
	
	printf("Min => %d , Max => %d\n",*min,*max);
	
	/* Sorts in ascending order*/
	for (i = 0; i < SIZE; i++) {
		getMin(&heap, (void **)&min);
		sorted[i] = *min;
		removeMin(&heap);
	}
	
	int prev = sorted[0];
	
	/* Is the array sorted ? */
	for (i = 1; i < SIZE; i++) {
		if (prev > sorted[i]) {
			printf("Random Array :(\n");
			break;
		}
		prev = sorted[i];
	}
	
	if (i == SIZE)
		printf("Sorted Array :D\n");
	
	
	destroyMinMaxHeap(&heap);
	
	return 0;
}
コード例 #8
0
BinaryNode *BinarySearchTree::removeMin(BinaryNode *t)
{
	if(t == NULL)
		throw 2;
	if(t->left != NULL)
		t->left = removeMin(t->left);
	else
	{
		BinaryNode *node = t;
		t = t->right;
		delete node;
	}
	return t;
}
コード例 #9
0
ファイル: dijkstra.c プロジェクト: junweiy/COMP20007-assn2
Set 
*dijkstra(Graph *g, Label v, int Home, int n) {
	// for the school vertex v, find all indices for homes and put all into
	// a set
	Heap *H;
	Edge *Eu;
	Set *S;
	int i, usize;
	Label u;
	float R[n], delta;
	// create a heap to store the distance for every vertices
	// and an array to store dist values
	H = createHeap();
	for (i=0;i<n;i++) {
		if (i==v) {
			insert(H, i, 0);
			R[i]=0;
			continue;
		}
		insert(H, i, INFINITY);
		R[i] = INFINITY;
	}
	// then loop through the heap
	while (H->n) {
		// extract the min in the heap
		u = removeMin(H);
		// if dist of u exceeds 1km, stop the loop
		if (R[u]>1000) {
			break;
		}
		Eu = graph_get_edge_array(g, u, &usize);
		for (i=0;i<usize;i++) {
			if (R[Eu[i].u]>R[u]+ *(float*)(Eu[i].data)) {
				delta = R[u] + *(float*)(Eu[i].data) - R[Eu[i].u];
				changeKey(H, Eu[i].u, delta);
				R[Eu[i].u] = R[u]+ *(float*)(Eu[i].data);
			}
		}
	}
	// now add all home indices with in the range of 1km into the set
	S = set_new();
	for (i=0;i<Home;i++) {
		if (R[i]<=1000) {
			set_add(S, i);
		}
	}
	return S;
}
コード例 #10
0
ファイル: lineMotions.cpp プロジェクト: Nekotonberry/me210
char followLine(int spd) {
	if (TMRArd_IsTimerExpired(LINE_FOLLOW_TIMER) != TMRArd_EXPIRED)
		return LINE_FOLLOW_OK;

	// reinit the timer
	TMRArd_InitTimer(LINE_FOLLOW_TIMER, LINE_FOLLOW_UPDATE_PERIOD);

	int val[3];
	char retVal;
	
	if (spd > 0)
		readFrontSensors(val);
	else
		readBackSensors(val);

	int min = removeMin(val);
	int max = getMax(val);
	int correction = 0;
	int error = getLinePos(val);

	// check min and max to determine
	// where all sensors covered, or all sensors on white
	
	if (min > LINE_SENSOR_MIN_THRES) {	// all black
		retVal = LINE_FOLLOW_ALL_LINE;
	}
	else if (max < LINE_SENSOR_MAX_THRES) {	// no line!
		retVal = LINE_FOLLOW_NO_LINE;
	}
	else {
		correction = (error * LINE_KP) >> 3;
		correction += (error - oldError) * LINE_KD;
		retVal = LINE_FOLLOW_OK;
	}

	if (spd > 0)
		adjustMotion(spd, -correction);
	else
		adjustMotion(-spd, -correction);
		
	oldError = error;

	return retVal;
}
コード例 #11
0
ファイル: principal.c プロジェクト: pemb/MC202
int main()
{
  char c;
  cliente entrada;
  while (scanf (" %c", &c) != EOF)
    {
      switch (c)
	{
	case 'A':
	  scanf (" %d", &entrada.dinheiro);
	  scanf (" %[^\n]", entrada.nome);
	  if (insere(entrada))
	    printf("Escritorio cheio\n");
	  break;
	case 'J':
	  if (clientes == 0)
	    {
	      printf("Escritorio vazio\n");
	      break;
	    }
	  entrada = pegaMin();
	  removeMin();	  
	  printf ("Joao vai atender %s (%d)\n", entrada.nome, entrada.dinheiro);
	  break;
	case 'M':
	  if (clientes == 0)
	    {
	      printf("Escritorio vazio\n");
	      break;
	    }
	  entrada = pegaMax();
	  removeMax();	  
	  printf ("Maria vai atender %s (%d)\n", entrada.nome, entrada.dinheiro);
	  break;
	case '#':
	  printf ("Ha %d clientes\n", clientes);
	  break;
	default:;
	}
    }
  return 0;
}
コード例 #12
0
BinaryNode *BinarySearchTree::rRemove(int x, BinaryNode *t) //throw (ItemNotFound)
{ 
	if(t == NULL)
		throw runtime_error("ITEM NOT FOUND");
	if(x < t->key)
		t->left = rRemove(x, t->left);
	else if(x > t->key)
		t->right = rRemove(x, t->right);
	else if(t->left != NULL && t->right != NULL)// item x is found; t has two children
	{
		t->key = findMin(t->right)->key;
		t->right = removeMin(t->right);
	} 
	else { //t has only one child
		BinaryNode *node = t;
		t = (t->left != NULL) ? t->left : t->right;
		delete node;
	}
	return t;
}
コード例 #13
0
ファイル: remove.cpp プロジェクト: kayhead996/Professional
Elem MySBBST<Elem, Key, EEComp, KEComp>::remove(MySBBSTNode *&sr, Key k) 
{
    Elem tmp = zero;
    if (KEComp::eq(k, (sr -> val)))
    {
        if (sr -> rc && sr -> lc)
        {
            tmp = sr -> val;
            sr -> val = removeMin(sr -> rc);
        }
        else if (sr -> rc)
        {
            tmp = sr -> val;
            sr = sr -> rc;
        }
        else if (sr -> lc)
        {
            tmp = sr -> val;
            sr = sr -> rc;
        } else {
            tmp = sr -> val;
            sr = NULL;
        }
        calcOrder(sr);
    } else if (KEComp::gt(k, (sr -> val)))
    {
        if (sr -> rc)
            tmp = remove(sr -> rc, k);
    } else if (KEComp::lt(k, (sr -> val)))
    {
        if (sr -> lc)
            tmp = remove(sr -> lc, k);
    }
        

    return tmp;
        
}
コード例 #14
0
ファイル: huffman.c プロジェクト: DerrickChanCS/COEN12
int main(int argc, char *argv[])
{
	int counts[257];	
	if(argc != 3)
	{
		printf("improper input\n");
		return 1;
	}
	FILE *in = fopen(argv[1], "r");
	if(in == NULL)
	{	
		printf("bad file name\n");
		return 2;
	}

	//set the values of aray to 0
	for(int i = 0; i < 257; i++)
	{
		counts[i] = 0;
	}

	//reads in characters
	int c = fgetc(in);
	while(c != EOF)
	{
		counts[c] += 1;
		c = fgetc(in);
	}

	//create heap
	//insert end of file marker
	node[256] = createTree(0, NULL, NULL);
	insert(node[256]);

	for(int i = 0; i < 257; i++)
	{
		//if the ASCII character appeared
		if(counts[i] != 0)
		{
			//create a new tree node
			node[i] = createTree(counts[i], NULL, NULL);
			insert(node[i]);
		}
	}	
	
	//constructing huffman tree
	while(heapSize > 1)
	{	
		//remove two lowest values, put them into a node, put the new node into the binary heap
		struct tree* left = removeMin();
		struct tree* right = removeMin();
		struct tree *tmp = createTree((getData(left) + getData(right)), right, left);
		insert(tmp);
	}

	for(int i = 0; i < 257; i++)
	{
		//print out the count and the codes of the ASCII characters
		if (node[i]!=NULL) {
			if(isprint(i))
				printf("'%c': %i ", i, getData(node[i]));
			else
				printf("%03o: %i ", i, getData(node[i]));
			code(node[i]);
			printf("\n");
		}
	}

	pack(argv[1], argv[2], node);//zip the file
	destroyTree(heap[0]);
	return 0;
}
コード例 #15
0
ファイル: a-star.c プロジェクト: MaxRoecker/AStar-MOA-UEM
int aStar(tNodeQueue *root, int heuristica, int *answer) {
    tQueue *a = malloc(sizeof(tQueue));
    tQueue *f = malloc(sizeof(tQueue));
    *answer = -1;
    printf("%d\n",a);
    initialize(a);
    initialize(f);


    insertAtEnd(a, root);

    while (!isEmpty(a)) {
        tNodeQueue *v = removeMin(a);
        insertAtEnd(f, v);

        if (isFinalState(v->elem->matrix)) {
            *answer = v->elem->f;
            return 1;
        } else {
            tNodeQueue *top = malloc(sizeof (tNodeQueue));
            tNodeBoard *topBoard = malloc(sizeof (tNodeBoard));
            top->elem = topBoard;
            tNodeQueue *right = malloc(sizeof (tNodeQueue));
            tNodeBoard *rightBoard = malloc(sizeof (tNodeBoard));
            right->elem = rightBoard;
            tNodeQueue *bottom = malloc(sizeof (tNodeQueue));
            tNodeBoard *bottomBoard = malloc(sizeof (tNodeBoard));
            bottom->elem = bottomBoard;
            tNodeQueue *left = malloc(sizeof (tNodeQueue));
            tNodeBoard *leftBoard = malloc(sizeof (tNodeBoard));
            left->elem = leftBoard;

            int i;
            int j;
            findZeroPosition(v->elem->matrix, &i, &j);
            if (moveTop(v->elem->matrix, top->elem->matrix, i, j)) {
                validSuccessor(a, f, v, top, heuristica);
            } else {
                free(topBoard);
                free(top);
            }
            if (moveRight(v->elem->matrix, right->elem->matrix, i, j)) {
                validSuccessor(a, f, v, right, heuristica);
            } else {
                free(rightBoard);
                free(right);
            }
            if (moveBottom(v->elem->matrix, bottom->elem->matrix, i, j)) {
                validSuccessor(a, f, v, bottom, heuristica);
            } else {
                free(bottomBoard);
                free(bottom);
            }
            if (moveLeft(v->elem->matrix, left->elem->matrix, i, j)) {
                validSuccessor(a, f, v, left, heuristica);
            } else {
                free(leftBoard);
                free(left);
            }

        }
    }
    if (isEmpty(a)) {
        return 0;
    }

}
コード例 #16
0
ファイル: search.c プロジェクト: kushpatel/CPSC223
heapNode dequeue(PQ *q) {
    heapNode rv = removeMin(q->heap, q->size);
    --q->size;
    return rv;
}
コード例 #17
0
ファイル: huffman.c プロジェクト: patback66/COEN12
int main(int argc, char *argv[])
{
    FILE *fpRead;
    int i, c, j;
    int count[257];
    TREE *leaves[257] = {NULL};
    TREE *heap[257] = {NULL};
    int heapCount = 0;
    
    //make sure read file and write file is specified
    if(argc < 3)
    {
        printf("Not all files are specified");
        return 0;
    }
    
    fpRead = fopen(argv[1], "r");
    
    //initialize charCount to zero
    for(i = 0; i < 257; i++)
    {
        count[i] = 0;
    }
    
    
    //increment character count for each character in the file.
    while((c=getc(fpRead))!=EOF)
    {
        count[c]++;
    }
    
    fclose(fpRead);
    
    //create and add leaves, set up to construct huffman tree
    for(j = 0; j < 256; j++)
    {
        if(count[j]>0)
        {
            leaves[j] = createTree(count[j], NULL, NULL);
            addSorted(heap, leaves[j], &heapCount);
        }
    }
    //add EOF char to the array
    leaves[256] = createTree(0, NULL, NULL);
    addSorted(heap, leaves[256], &heapCount);
    
    //construct the huffman tree
    while(heapCount>1)
    {
        TREE *smallMin = removeMin(heap, &heapCount);
        TREE *bigMin = removeMin(heap, &heapCount);
        TREE *combo = createTree(getData(smallMin)+getData(bigMin), smallMin, bigMin);
        //addSorted(heap, combo, &heapCount);
        addSorted(heap, combo, &heapCount);
    }
    
    for(i = 0; i < 257; i++)
    {
        if(leaves[i]!=NULL)
        {
            if(isprint(i))
                printf("'%c': %d\t", i, getData(leaves[i]));
            else
                printf("%03o: %d\t", i, getData(leaves[i]));
            printTree(leaves[i]);
            printf("\n");
        }
    }
    pack(argv[1] , argv[2], leaves);
    //add leaves to heap
    //length 257
    //add and remove functions
    //get mins, use createTree to then make a tree wtih the minimun values as children of the new combined root node
    
    //build the heap
    //heap of size size, initialized to null
    //keep heap count
    //for -> traverse through leaves, if leaves[index] != NULL
    //insertHeap -> min heap, increment heap count
    //after all inserted, assemble priority queue into huffman tree
    //insert and delete -> dequeue
    //in heap, remove first two minimums so dequeue those
    //sum of the two becomes a new tree, decrement tree
    //make sure to remove from top so take from the rightmost from the left then shift the others from the bottom
    //set what was removed from the end to null
    //last two steps after creating the tree
    //iterate until only 1 tree left which is final huffman tree
    //print out bit pattern for each char
    //pass leaves into pack function
    //free the memory associated with huffman tree
    //start with eof
    //while(getParent(root)!=NULL, root=getParent(root); call destroyTree;
}
コード例 #18
0
void PriorityQueue::clearAll() {
    while(!empty()) {
        removeMin();
    }
}
コード例 #19
0
ファイル: dequeue.c プロジェクト: Jobbernowle/PriorityQueue
void* dequeue(t_pQueue* p, t_comp c)
{
  return removeMin(p->h, c);
}