コード例 #1
0
ファイル: dijkstra.c プロジェクト: doudouOUC/algorithms
void dijkstra(MGraph *G, int s)
{
    int i, *set, u, v;
    MinQueue queue;
    initialize_single_source(G, s);
    set = malloc(sizeof(int)*G->numVertexes);
    queue.size = G->numVertexes;
    queue.heap = malloc(sizeof(int)*(G->numVertexes+1));
    //初始化集合S为空
    for(i=0;i<G->numVertexes;i++)
    {
        set[i] = 0;
    }
    set[s] = 1;
    //初始化队列为空
    for(i=0;i<G->numVertexes;i++)
    {
        queue.heap[i+1] = i;
    }
    
    //逐步添加最小权值边
    while(queue.size>0)
    {
        build_min_heap(&queue);
        u = extract_min(&queue);
        set[u] = 1;
        for(i=0;i<G->numVertexes;i++)
        {
            if(G->edges[u][i] != INFINITY)
            {
                relax(u,i, G->edges[u][i]);
            }
        }
    }
}
コード例 #2
0
ファイル: heaparray.C プロジェクト: ppeiris/Algorithms
int main()
{
	int A[] = {8, 1, 3, 2, 16, 9, 10, 14, 4, 7};
	int length = sizeof(A)/sizeof(int);

	printf("1. build a max heap\n");
	printf("2. build a max heap and sort (heap sort)\n");
	printf("3. build a min heap\n");
	int input = 0;
	scanf("%d", &input);

	printA(A, length);

	switch(input) {
		case 1:
			build_max_heap(A, length);
			printA(A, length);
			break;
		case 2:
			build_max_heap(A, length);
			max_heapsort(A, length);
			printA(A, length);
			break;
		case 3:
			build_min_heap(A, length);
			printA(A, length);
			break;
	}

	return 0;
}
コード例 #3
0
ファイル: heap.c プロジェクト: minggr/backup
int main()
{
	int data[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
	int size = 10;
	//int *data = malloc(sizeof(int)*size);
	struct heap *h;
	int new_data = 30;

	h = build_max_heap(data, size);
	dump_heap(h);
	free(h);

	h = build_min_heap(data, size/2, size);
	dump_heap(h);
	printf("extract min=%d\n", min_heap_extract(h));
	dump_heap(h);
	printf("insert %d\n", new_data);
	min_heap_insert(h, new_data);
	dump_heap(h);
	free(h);

	//free(data);

	return 0;
}
コード例 #4
0
ファイル: heap.c プロジェクト: alldroll/my_binary_heap
void heapsort(SequenceT* arr, size_t size, SortOrderT order) {
    if (arr == NULL || size <= 1) {
        return;
    }

    HeapT* h = create_heap_from(arr, size);
    assert(h != NULL);
    HeapImplT* heap = (HeapImplT*) h;
    void (*heapify)(HeapT*, size_t);

    if (order == DESC) {
        build_max_heap(h);
        heapify = max_heapify;
    } else {
        build_min_heap(h);
        heapify = min_heapify;
    }

    size_t index = size - 1;
    for (; index > 0; --index) {
        swap(&heap->data[index], &heap->data[0]);
        --heap->size;
        heapify(h, 0);
    }

    memcpy(arr, heap->data, size * sizeof(SequenceT));
    destroy_heap(h);
}
コード例 #5
0
ファイル: heapsort.c プロジェクト: kushagra06/algorithms
int main()
{
    int i;
    scanf("%d",&n);//input no. of elements
    int A[n+1];
    sz=n;
    A[0]='\0';
    for(i=1;i<=n;i++)
        scanf("%d",&A[i]);//enter elements
    build_min_heap(A,n);
    heapsort(A,n);
    return 0;
}
コード例 #6
0
ファイル: dijkstra2.c プロジェクト: cheerayhuang/BOOK_ITA
void dijkstra(WEIGHT weight, int len, int src) 
{
    INFO_OF_NODE info; 

    init_node_info(info, len, src); 

    HEAP heap; 

    int i; 
    for(i = 0; i < len; ++i) 
        heap[i] = i; 

    build_min_heap(heap, info, len);
    
    int rear = len; 

    while(rear > 0) {

        int q = heap[0]; 
        info[q].color = BLACK; 

        heap[0] = heap[--rear]; 
        heap[rear] = q; 

        keep_heap_property(heap, info, 0, rear); 

        int i; 
        for(i = 0; i < len; ++i) {
            
            //cause dijkstra can't support negative weight. 
            if(weight[q][i] > 0 && info[i].color == WHITE) {
                relax_edge(q, i, heap, info, weight); 
            }

        }

    }

    for(i = 0; i < len; ++i) {
        
        print_shortest_path(info, i, src); 

        if(info[i].path_len == LONG_MAX) 
            printf(" can't reach.\n"); 
        else 
            printf(" weight of path = %d\n", info[i].path_len); 

    }
}
コード例 #7
0
ファイル: AC_3253.c プロジェクト: simplyzhao/Code_Pearls
long long
huffman_tree_way(long long *heap, int length)
{
    int i;
    long long fst, snd, sum, rt=0;
    build_min_heap(heap, length);
    for(i=0; i<length-1; i++) {
        fst = extract_min(heap);
        snd = extract_min(heap);
        sum = fst + snd;
        rt += sum;
        insert(heap, sum);
    }
    return rt;
}
コード例 #8
0
DijkstraResult* dijkstra(Graph *graph, int source){
    DijkstraResult* dijkstra_result;
    MinPriorityQueue min_priority_queue;
    int u;
    dijkstra_result = allocate_memory_dijkstra(graph->numbers_nodes);
    allocate_memory(&min_priority_queue, graph->numbers_nodes);
    initialize(dijkstra_result, &min_priority_queue, source, graph->numbers_nodes);
    build_min_heap(&min_priority_queue);
    while(lenght(&min_priority_queue) > 0){
        u = extract_minimum(&min_priority_queue);
        for(int v = 0; v < graph->numbers_nodes; v++)
            relax(dijkstra_result, &min_priority_queue, graph, u, v);
    }
    return dijkstra_result;
}; 
コード例 #9
0
ファイル: MinHeap.c プロジェクト: amatteson89/MinHeapSort
int main(){
	time_t start,end;
	float diff = 0;
	FILE * fin = fopen("data.txt", "r");
	Node min_heap_array[MIN_HEAP_SIZE];
	int index_count = 1;

	start = clock();	

	for(int i = 1; i < MIN_HEAP_SIZE; i++ ){
		min_heap_array[i].value = NEG_INFINITY;
	}

	for(int i = 1; i < MIN_HEAP_SIZE; i++){
		fscanf(fin, "%d", &(min_heap_array[i].value) ) ;
		min_heap_array[index_count].index = index_count;
		index_count++;
	}

	build_min_heap(min_heap_array);

	while( !feof(fin)){
		int temp = 0;

		fscanf(fin, "%d", &temp);

		//See if the next number is bigger than smallest in the heap
		if(temp > min_heap_array[1].value){
			min_heap_array[1].value = temp; //replace the smallest in the heap
			min_heap_array[1].index = index_count;
			min_heapify(min_heap_array, 1);
		}
		index_count++;
	}
		

	//PRINT OUT THE HEAP
	//for(int i = MIN_HEAP_SIZE; i > 0; i--)
	//	printf("node %d: %d at index: %d\n", i, min_heap_array[i].value, min_heap_array[i].index);
	

	end = clock();
	diff = (float)end - (float)start;
	printf("Running time: %f\n", diff/ CLOCKS_PER_SEC);
	fclose(fin);

	return 0;
}
コード例 #10
0
ファイル: huffman_s.c プロジェクト: bysun2013/algorithm
/*
 * it returns the weight of huffman code, does not build huffman tree
 * */
static int huffman(pqueue *pq)
{
	int weight = 0;
	int t1, t2;
	int p;

	build_min_heap(pq);
	while(pq->size > 1){
		t1 = extract_min(pq);
		t2 = extract_min(pq);
		p = t1 + t2;
		insert_pqueue(pq, p);
		weight += p;
	}

	return weight;
}
コード例 #11
0
void min_heapSort(symbol s[], int lastIndex)
{
    int index;
    symbol temp;

    //build_max_heap(s, lastIndex);
    build_min_heap(s, lastIndex);

    // put smallest element (root) into last leaf's position,
    // then min_heapify the heap ONE LEAF LESS IN SIZE --in other words,
    // leave the leaf you just moved untouched by the next heapify.
    for ( index = lastIndex; index >= 1; index-- )
    {
        temp     = s[0]; // temporarily store biggest element (from root)
        s[0]     = s[index]; // put last element (smallest) into root position
        s[index] = temp; // put biggest element into last position
        min_heapify(s, 0, index-1); // min_heapify "i-1"-sized heap
        //max_heapify(s, 0, index-1); // max_heapify "i-1"-sized heap
        // (leave out the leaf you just did)
    }
}
コード例 #12
0
ファイル: TAD_GRAFO.c プロジェクト: gioknx/AEDS-3
void Djkistra(Grafo* grafo, int s){
	// Inicializamos a distancias de todos os veritces com um numero muito grande
	inicializa_fonte_unica(grafo, s);
	int i, u;
	
	// Colocamos todos os vertices como não visitados
	for(i=0;i<grafo->tamanho;i++)
		grafo->lista[i]->S = 0;

	// Adiciona todos os vértices do grafo no heap
	Heap *heap = inicializa_heap(grafo->tamanho);
	for(i=0;i<grafo->tamanho;i++){
		adiciona_heap(heap, i+1, grafo->lista[i]->d, i);
	}
	// Construimos o heap
	build_min_heap(heap);

	Vertice *aux;
//	int numero_adj;
	while(heap->tamanho != 0){
		// Extrai o vértice com a menor distancia da origem
		u = extract_min(heap);

		// Coloca esse vértice no conjunto dos visitados
		grafo->lista[u]->S = 1;
		
		// Aux caminhará pelos adjacentes a u
		aux = grafo->lista[u]->prox;


			while(aux != NULL){
				if(grafo->lista[aux->valor]->S == 0)
					relax(heap, grafo, u, aux->valor);
				aux = aux->prox;
			}
		}
		libera_heap(heap);
	}
コード例 #13
0
int main (int argc, const char * argv[])
{

    int array[MAXLEN];
    for (int i = MAXLEN; i > 0; i--) {
        array[MAXLEN - i] = i;
    }
    for (int j = 0; j < MAXLEN; j++) {
        printf("%d ",array[j]);
    }
    printf("\n");
    //build the min heap
    build_min_heap(array, MAXLEN);
    
    for (int j = 0; j < MAXLEN; j++) {
        printf("%d ",array[j]);
    }
    printf("\n");
    get_k_min(array, K, MAXLEN);
    
    printf("Hello, World!\n");
    return 0;
}
コード例 #14
0
int main(int argc, char *argv[])
{
    // Receive pairs of ints input to this program, save into struct array
    int numSymbols = 0;
    while ( scanf("%d", &s[numSymbols].freq) == 1 )
    {
        s[numSymbols].letter = numSymbols;
        t[numSymbols].freq   = s[numSymbols].freq; // Store into hufftree, too.
        numSymbols++;
    }

    printf("\n");


    // these will be incremented/decremented at various times,
    // but 'originalSize' shall not be changed.
    int originalSize = numSymbols;
    int heapSize     = numSymbols;
    /*
      printf("This is how we received all the numbers:\n");
      int i;
      for (i=0; i<numSymbols ; i++)
      {
        printf("%5d ", s[i].freq);
        printf("is the freq of letter: %d\n", s[i].letter);
      }
    */


    build_min_heap(s, heapSize-1);
    /*
      printf("This is the heap:\n");
      //int i;
      for (i=0; i<numSymbols ; i++)
      {
        printf("%5ld ", s[i].freq);
        printf("%d\n", s[i].letter);
      }
    */
    // watch out: heapSize will shrink
    // ---------  numSymbols with grow
    // ...but they start out equal.
    //printf("heapSize: %d\n", heapSize);
    while (heapSize>=2)
    {
        symbol thing1 = min_heap_extract(s, &heapSize);
        //printf("AFTER EXTRACT heapSize: %d\n", heapSize);
        //printf("thing1.letter: %d\n", thing1.letter);
        //printf("thing1.freq: %d\n", thing1.freq);
        symbol thing2 = min_heap_extract(s, &heapSize);
        //printf("AFTER EXTRACT heapSize: %d\n", heapSize);
        //printf("thing2.letter: %d\n", thing2.letter);
        //printf("thing2.freq: %d\n", thing2.freq);
        symbol new_thing;
        new_thing.letter = numSymbols;
        new_thing.freq   = thing1.freq + thing2.freq;
        //printf("new_thing.letter: %d\n", new_thing.letter);
        //printf("new_thing.freq: %d\n", new_thing.freq);

        //printf("^^^^^^^^^^^^^^fidlin' with the t tree^^^^^^^^^^^^\n");
        t[thing1.letter].parent      = numSymbols;
        //printf("t[%d].parent: %d\n", thing1.letter, t[thing1.letter].parent);
        t[thing1.letter].zero_or_one = 0;
        //printf("t[%d].zero_or_one: %d\n", thing1.letter, t[thing1.letter].zero_or_one);
        t[thing2.letter].parent      = numSymbols;
        //printf("t[%d].parent: %d\n", thing2.letter, t[thing2.letter].parent);
        t[thing2.letter].zero_or_one = 1;
        //printf("t[%d].zero_or_one: %d\n", thing2.letter, t[thing2.letter].zero_or_one);
        t[numSymbols].parent         = -1;
        //printf("t[%d].parent: %d\n", numSymbols, t[numSymbols].parent);
        numSymbols++;
        heapSize++; // doesn't get modified by insert function, do it manually here
        min_heap_insert(s, heapSize-1, new_thing);
        //printf("AFTER INSERT heapSize: %d\n", heapSize);
        /*
            printf("This is the heap:\n");
            //int i;
            for (i=0; i<heapSize ; i++)
            {
              printf("%5ld ", s[i].freq);
              printf("%d\n", s[i].letter);
            }
        */
    }

    /* If the given frequencies of letters were actually used,
       print the number of bits needed to huffman-encode the whole thing. */
    int i;
    int tally = 0;
    for (i=0; i<originalSize; i++)
    {
        t[i].numBits = getBits(i);
        tally = tally + t[i].numBits * t[i].freq;
    }
    printf("%d\n", tally);


    // print the huffman codes of each given letter
    for (i=0; i<originalSize; i++)
    {
        printf("%c ", i+'A');
        print(i);
        printf("\n");
    }











    /*
      symbol x = min_heap_extract(s, &numSymbols);
      printf("the min node has value: %d\n", x.freq);

      printf("numSymbols is now %d\n", numSymbols);
      printf("This is the heap after extracting:\n");
      //int i;
      for (i=0; i<numSymbols ; i++)
      {
        printf("%5ld ", s[i].freq);
        printf("%d\n", s[i].letter);
      }

      x = min_heap_extract(s, &numSymbols);
      printf("the min node has value: %d\n", x.freq);

      printf("numSymbols is now %d\n", numSymbols);
      printf("This is the heap after extracting again:\n");
      //int i;
      for (i=0; i<numSymbols ; i++)
      {
        printf("%5ld ", s[i].freq);
        printf("%d\n", s[i].letter);
      }



      //TESTING INSERT
      symbol woof;
      woof.freq = 17;
      woof.letter = 17;
      numSymbols++;
      min_heap_insert(s, numSymbols, woof);
      printf("===================does INSERT work?====================\n");
      x = min_heap_minimum(s);
      printf("woof node has value: %d\n", woof.freq);
      printf("the min node has value: %d\n", x.freq);
      printf("numSymbols is now %d\n", numSymbols);
      printf("This is the heap after inserting:\n");
      //int i;
      for (i=0; i<numSymbols ; i++)
      {
        printf("%5ld ", s[i].freq);
        printf("%d\n", s[i].letter);
      }

    */

    /*
      //  heapSort(s, numSymbols-1);
      min_heapSort(s, numSymbols-1);

      printf("This is how how it looks after sorting:\n");
      for (i=0; i<numSymbols ; i++)
      {
        printf("%5d ", s[i].freq);
        printf("for letter %d\n", s[i].letter);
      }

    */


    printf("\n");


}
コード例 #15
0
int main()
{
	freopen("input.txt","r",stdin);

	char str[500];
	scanf("%s",str);
	char visit[26];
	node* ptr[26];
	int i,l = strlen(str),j=1,k;

	for(i=0; i<26; i++)
		visit[i] = 0;

	/*for(i=0; i<l; i++)
		freq[str[i]-'A']++;*/

	heap min_queue;
	min_queue.length = 0;
	node *n1, *n2, *n;

	for(i=0; i<l; i++)
	{
		k = str[i]-'A';
		if(visit[k] == 0)
		{
			visit[k] = 1;
			ptr[k] = min_queue.arr[j++] = get_node(str[i], 1);//made changes here inplace of i use j for min_queue arr
			min_queue.length++;
		}
		else
		{
			ptr[k]->freq++;
		}
	}

	/*for(i=0; i<min_queue.length; i++)
		print_node(min_queue.arr[i+1]);
*/
	build_min_heap(&min_queue);

	/*for(i=0; i<min_queue.length; i++)
		print_node(min_queue.arr[i+1]);*/

	/*n1 = heap_extract_min(&min_queue);
		print_node(n1);
		n2 = heap_extract_min(&min_queue);
		print_node(n2);

		printf("ABCD\n");

	for(i=0; i<min_queue.heap_size; i++)
		print_node(min_queue.arr[i+1]);*/

	while(min_queue.heap_size >= 2)
	{
		n1 = heap_extract_min(&min_queue);
		print_node(n1);
		n2 = heap_extract_min(&min_queue);
		print_node(n2);
		n = get_node('0',0);
		n->freq = n1->freq + n2->freq;
		n->lchild = n1;
		n->rchild = n2;
		n1->isleft = 1;
		n2->isleft = 0;
		n1->parent = n2->parent = n;
		min_heap_insert(&min_queue,n);
	}

	printf("%d\n", count);
	n = heap_extract_min(&min_queue);
	postorder(n);
	printf("\n");
	inorder(n);
	printf("\n");
	for(i=0; i<l; i++)
	{
		huff_code(ptr[str[i]-'A']);
	}

		/*ENDDDDDDDDDDDDDDDDDD
	/*print_node(n);
	printf("\n");
	print_node(n->lchild);
	printf("\n");
	print_node(n->rchild);
	printf("\n");
	print_node(n->rchild->lchild);
	printf("\n");
	print_node(n->rchild->rchild);
	printf("\n");
	print_node(n->rchild->rchild->lchild);
	printf("\n");
	print_node(n->rchild->rchild->rchild);*/

	//Used for checking if Prority Queue is working fine
	/*while(min_queue.heap_size >= 1)
	{
		node* tmp = heap_extract_min(&min_queue);
		printf("%c-%d\n",tmp->ch, tmp->freq);
	}*/

	return 0;
}