void dijkstra(struct Graph *graph, int src)
{
	int v = graph->v, i;
	int pr;

	for(i = 0; i < v; i++)
	{
		pr = 50000;
		insert(i, pr);
	}

	decreaseKey(src, 0);
	while(!isEmptyminHeap())
	{
		extract_min(heap);
		int x = min_vertex, y = min_dist;

		struct adjListNode *vertex = graph->array[x].head;
		while(vertex != NULL)
		{
			int v = vertex->node;
			if(isInMinHeap(v) && y != 50000 && vertex->weight + y < get_priority(v))
			{
				pr = y + vertex->weight;
				decreaseKey(v, pr);
			}
			vertex = vertex->next;
		}
	}
	// printArray(graph);
}
Exemple #2
0
void testDecreaseKey() {
    printf("Test 4. decreaseKey: ");
    MinHeap heap;
    int tmp[] = {2,3,4};
    heap.size = 3;
    for (unsigned int i = 0; i < heap.size; i++) {
        heap.array[i] = tmp[i];
    }

    decreaseKey(&heap, 2, 1);

    int res1[3] = {1,3,2};

    if (!cmpArray(heap.array, res1, 3) || (heap.size != 3)) {
        printf("NOK - chyba ve funkci decreaseKey\n");
    } else {
        decreaseKey(&heap, 0, 4);
        if (!cmpArray(heap.array, res1, 3) || (heap.size != 3)) {
            printf("NOK - chyba ve funkci decreaseKey\n");
        } else {
            printf("OK\n");
        }
    }
    makeGraph(&heap, "decrease.dot");
    printf("Vykreslenou haldu najdete v souboru decrease.dot\n");
}
Exemple #3
0
// The main function that calulates distances of shortest paths from src to all
// vertices. It is a O(ELogV) function
void dijkstra(struct Graph* graph, int src)
{
    int V = graph->V;// Get the number of vertices in graph
    int dist[V];      // dist values used to pick minimum weight edge in cut
 
    // minHeap represents set E
    struct MinHeap* minHeap = createMinHeap(V);
 
    // Initialize min heap with all vertices. dist value of all vertices 
    for (int v = 0; v < V; ++v)
    {
        dist[v] = INT_MAX;
        minHeap->array[v] = newMinHeapNode(v, dist[v]);
        minHeap->pos[v] = v;
    }
 
    // Make dist value of src vertex as 0 so that it is extracted first
    minHeap->array[src] = newMinHeapNode(src, dist[src]);
    minHeap->pos[src]   = src;
    dist[src] = 0;
    decreaseKey(minHeap, src, dist[src]);
 
    // Initially size of min heap is equal to V
    minHeap->size = V;
 
    // In the followin loop, min heap contains all nodes
    // whose shortest distance is not yet finalized.
    while (!isEmpty(minHeap))
    {
        // Extract the vertex with minimum distance value
        struct MinHeapNode* minHeapNode = extractMin(minHeap);
        int u = minHeapNode->v; // Store the extracted vertex number
 
        // Traverse through all adjacent vertices of u (the extracted
        // vertex) and update their distance values
        struct AdjListNode* pCrawl = graph->array[u].head;
        while (pCrawl != NULL)
        {
            int v = pCrawl->dest;
 
            // If shortest distance to v is not finalized yet, and distance to v
            // through u is less than its previously calculated distance
            if (isInMinHeap(minHeap, v) && dist[u] != INT_MAX && 
                                          pCrawl->weight + dist[u] < dist[v])
            {
                dist[v] = dist[u] + pCrawl->weight;
 
                // update distance value in min heap also
                decreaseKey(minHeap, v, dist[v]);
            }
            pCrawl = pCrawl->next;
        }
    }
 
    // print the calculated shortest distances
    printArr(dist, V);
}
Exemple #4
0
int dijkstra(PWDG graph, int src, int dst) {

  int V = graph->count;
  int dist[V];

  // Clone node:
  if (src == dst) {
    wdg_clone(graph, src);
    dst = V; V++;
  }

  pMinHeap minHeap = createMinHeap(V);

  for (int v=0; v<V; ++v) {
    dist[v] = INT_MAX;
    minHeap->array[v] = newMinHeapNode(v, dist[v]);
    minHeap->pos[v] = v;
  }

  dist[src] = 0;
  decreaseKey(minHeap, src, dist[src]);
  minHeap->size = V;

  while (!isEmpty(minHeap)) {

    pMinHeapNode minHeapNode = extractMin(minHeap);
    int u = minHeapNode->v;

    if (u == dst) {
      wdg_unclone(graph);
      return dist[u];
    }

    PNODE pCrawl = graph->list[u].head;

    while (pCrawl != NULL) {

      int v = pCrawl->dst;

      if (isInMinHeap(minHeap, v) && dist[u] != INT_MAX && pCrawl->wgt + dist[u] < dist[v]) {
        dist[v] = dist[u] + pCrawl->wgt;
        decreaseKey(minHeap, v, dist[v]);
      }

      pCrawl = pCrawl->next;
    }
  }

  #ifdef DEBUG
  printArr(dist, V, src);
  #endif

  wdg_unclone(graph);
  return -1;
}
void
dijkstra(graph* g, int src)
{
    int v, V = g->V; // getting the number of indices from the graph.
    int dist[V];
    int i,max = 0;

    minHeap* mHeap = createMinHeap(V);

    for(v = 0; v < V; v++)
    {
        dist[v] = MAXINT;
        mHeap->array[v] = createHeapNode(v, dist[v]);
        mHeap->pos[v] = v;
    }
    mHeap->array[src] = createHeapNode(src, dist[src]);
    mHeap->pos[src]   = src;
    dist[src] = 0;
    decreaseKey(mHeap, src, dist[src]);

    mHeap->size = V;

    while ((mHeap->size!=0))
    {
        minHeapNode* mHeapNode = extractMin(mHeap);
        int u = mHeapNode->v;

        node* pNode = g->array[u].head;
        while (pNode != NULL)
        {
            int v = pNode->d;

            if ((isInMinHeap(mHeap, v) && dist[u] != MAXINT) && ((pNode->w + dist[u]) < dist[v]))
            {
                dist[v] = dist[u] + pNode->w;
                decreaseKey(mHeap, v, dist[v]);
            }
            pNode = pNode->next;
        }
    }

    //print the shortest path from distant vertex
    for(i = 0; i < V; i++)
    {
        if(max < dist[i])
            max = dist[i];
    }

    printf("most distant vertex is %d\n",max);
}
/*
 * @brief Inserts a new Element to minHeap
 *
 * @param id a string containing data to be associated with a key
 * @param key an integer associated with a particular string id
 *
 * @return nothing
 *
 * Creates a new Element with the given id and INT_MAX for the key,
 * pushes the Element onto the end of minHeap, then calls decreaseKey
 * with the given key to adjust the key correctly and get the Element
 * into the right place within the minHeap.
 */
void MinPriorityQ::insert(string id, int key) {
    Element* temp = new Element();
    temp->id = id;
    temp->key = INT_MAX;
    minHeap.push_back(temp);
    decreaseKey(id, key);
}
// The main function that constructs Minimum Spanning Tree (MST)
// using Prim's algorithm
void PrimMST(struct Graph* graph)
{
    int V = graph->V;// Get the number of vertices in graph
    int parent[V];   // Array to store constructed MST
    int key[V];      // Key values used to pick minimum weight edge in cut
 
    // minHeap represents set E
    struct MinHeap* minHeap = createMinHeap(V);
 
    // Initialize min heap with all vertices. Key value of
    // all vertices (except 0th vertex) is initially infinite
    for (int v = 1; v < V; ++v)
    {
        parent[v] = -1;
        key[v] = INT_MAX;
        minHeap->array[v] = newMinHeapNode(v, key[v]);
        minHeap->pos[v] = v;
    }
 
    // Make key value of 0th vertex as 0 so that it
    // is extracted first
    key[0] = 0;
    minHeap->array[0] = newMinHeapNode(0, key[0]);
    minHeap->pos[0]   = 0;
 
    // Initially size of min heap is equal to V
    minHeap->size = V;
 
    // In the followin loop, min heap contains all nodes
    // not yet added to MST.
    while (!isEmpty(minHeap))
    {
        // Extract the vertex with minimum key value
        struct MinHeapNode* minHeapNode = extractMin(minHeap);
        int u = minHeapNode->v; // Store the extracted vertex number
 
        // Traverse through all adjacent vertices of u (the extracted
        // vertex) and update their key values
        struct AdjListNode* pCrawl = graph->array[u].head;
        while (pCrawl != NULL)
        {
            int v = pCrawl->dest;
 
            // If v is not yet included in MST and weight of u-v is
            // less than key value of v, then update key value and
            // parent of v
            if (isInMinHeap(minHeap, v) && pCrawl->weight < key[v])
            {
                key[v] = pCrawl->weight;
                parent[v] = u;
                decreaseKey(minHeap, v, key[v]);
            }
            pCrawl = pCrawl->next;
        }
    }
 
    // print edges of MST
    printArr(parent, V);
}
BinomialHeap *BinomialHeap::deleteNode(BinomialHeap &bh, void* target)
{
    void *minValue=getmin(this->size);
    int b = INT_MIN;
    void *p = &b;
    decreaseKey(bh,target,p); //conseguir el valor minimo de acuerdo al size
    extractMin(bh);
}
bool BinaryHeap :: updateKey(Location nodeAddress, Priority newKey)
{
 BinaryNode * node;
 if(nodeAddress == NULL) return false;
 node = (BinaryNode *) nodeAddress;
 if (newKey < node->key)
    return decreaseKey(nodeAddress,newKey);
 else if (newKey > node->key)
    return increaseKey(nodeAddress,newKey);
 else
    return true;

}
// delete the given node from the heap
bool BinaryHeap :: deleteKey(Location nodeAddress)
{
  BinaryNode *x,*z,*y=(BinaryNode*)nodeAddress;
  Priority datakey =lastElement->key;
  x=lastElement;

  //updation of pointers
  if(root==NULL || y==NULL )
    return false;
  else if(y==root && y->leftChild==NULL && y->rightChild==NULL)
    root=lastElement=NULL;
  else if(x->parent->rightChild==x){
    x->parent->rightChild=NULL;
    lastElement=x->parent->leftChild;
    x->leftSibling->rightSibling=NULL;
  }
  else if(x->parent->leftChild==x)
    {
      x->parent->leftChild=NULL;
      if(x->parent==root)
	lastElement=root;
      else
	{
	  if(x->parent->leftSibling==NULL)
	    {
	      z=x->parent;
	      while(z->rightSibling!=NULL)
		{
		  z=z->rightSibling;
		}
	      lastElement=z;
	    }
	  else{
	    lastElement=x->parent->leftSibling->rightChild;
	    x->parent->leftSibling->rightChild->rightSibling=NULL;
	  }
	}

    }
  keyToAddress.erase(x->key);
  delete x; //delete the node
  // heapify the given heap
  if(y->key < datakey)
    increaseKey(y,datakey);
  else if(y->key > datakey)
    decreaseKey(y,datakey);
  return true;
}
void insertMinHeap( struct MinHeap * minHeap, int element, int priority ) {

	struct MinHeapNode * node = createNewMinHeapNode(element, INT_MAX);

	// set the new index of this element
	minHeap -> current_position[element] = minHeap -> current_size;

	// set this node to array of pointers
	minHeap -> array[minHeap -> current_size] = node;

	// increase the size 
	minHeap -> current_size += 1;

	// decrease the priority of this element to priority
	decreaseKey(minHeap, element, priority);

}
// decrease the given key by a given value
bool BinaryHeap :: decreaseKey(Location nodeAddress, Priority newKey)
{
  BinaryNode *y=(BinaryNode*)nodeAddress;
  if(y==NULL || (newKey >= y->key)) //check for a invalid input
    return false;
  else{
    y->key=newKey; //change the key in the heap
    setLocation(y,y->key);
    // update the parent if required
    if(y->parent!=NULL && y->parent->key > newKey){
      y->key=y->parent->key;
      setLocation(y,y->key);
      // recursive call on the parent to trill up the key upto the root
      decreaseKey(y->parent,newKey);
    }
  }
  return true;
}
Exemple #13
0
int  FibHeap::remove(FibHeapNode *theNode)
{
  FibHeapNode Temp;
  int Result;
  
  if (theNode == NULL) return NOTOK;
  
  Temp.m_neg_infinity_flag = 1;
  Result = decreaseKey(theNode, Temp);
  
  if (Result == OK)
    if (extractMin() == NULL) Result = NOTOK;
    
    if (Result == OK) {
      if (getHeapOwnership()) delete theNode;
      else theNode->m_neg_infinity_flag = 0;
    }
    
    return Result;
}
Exemple #14
0
void Prims(int source){
	struct node* adjacent;
	int min;
	CreateHeap(vertices);

	insert(0,source);
	AdjacencyList[source].pri = 0;
	min = extractMin();
	AdjacencyList[min].color = BLUE;
	pi[source] = source;
	while(min!=-1){
	adjacent = AdjacencyList[min].Node;
	while(adjacent!=NULL){

		if(AdjacencyList[adjacent->vertex].color == RED){
			AdjacencyList[adjacent->vertex].pri = adjacent->weight;
			AdjacencyList[adjacent->vertex].color = YELLOW;
			pi[adjacent->vertex] = min;
			insert(AdjacencyList[adjacent->vertex].pri,adjacent->vertex);
		}
		else if(AdjacencyList[adjacent->vertex].color == YELLOW){
			//printf("Here for %d\n,weight = %d,",adjacent->vertex,adjacent->weight);
			if(AdjacencyList[adjacent->vertex].pri > adjacent->weight)
			{
				AdjacencyList[adjacent->vertex].pri = adjacent->weight;
				decreaseKey(AdjacencyList[adjacent->vertex].HeapPoint , AdjacencyList[adjacent->vertex].pri);
				pi[adjacent->vertex] = min;
			}
		}
		adjacent = adjacent->next;
	}
	min = extractMin();	
	if(min!=-1)
	AdjacencyList[min].color = BLUE;
	//printf("Minimum = %d\n",min);
}

}
//deleting the element under index 
void deleteElement(int index, BinaryHeap bh)
{
	decreaseKey(index, Infinity, bh); // 1st step, decreaseKey operation placing the element under index upto the root	
	deleteMin(bh); //2nd step, deleteMin deleting the element under the root;
} 
Exemple #16
0
// The main function that constructs Minimum Spanning Tree (MST)
// using Prim's algorithm
void PrimMST(Graph* graph)
{
    int MSTWeight = 0;
    int V = graph->V;// Get the number of vertices in graph
    int E = graph->E;// Get the number of edges in graph
    int parent[V];   // Array to store constructed MST
    int key[V];      // Key values used to pick minimum weight edge in cut
 
    // minHeap represents set E
    MinHeap* minHeap = createMinHeap(V);
 
    // Initialize min heap with all vertices. Key value of
    // all vertices (except 0th vertex) is initially infinite

    // print edges of MST
    printf("===============================================\n");
    printf("Following are the edges in the constructed MST\n");

    for (int v = 1; v < V; ++v)
    {
        parent[v] = -1;
        key[v] = INT_MAX;
        minHeap->array[v] = newMinHeapNode(v, key[v]);
        minHeap->pos[v] = v;
    }
 
    // Make key value of 0th vertex as 0 so that it
    // is extracted first
    key[0] = 0;
    minHeap->array[0] = newMinHeapNode(0, key[0]);
    minHeap->pos[0]   = 0;
 
    // Initially size of min heap is equal to V
    minHeap->size = V;
 
    // In the followin loop, min heap contains all nodes
    // not yet added to MST.
    while (!isEmpty(minHeap))
    {
        // Extract the vertex with minimum key value
        MinHeapNode* minHeapNode = extractMin(minHeap);
        int u = minHeapNode->v; // Store the extracted vertex number
        // Traverse through all adjacent vertices of u (the extracted
        // vertex) and update their key values
	int i;
	int* adjList = findAdjList(graph,u);
        int size = findAdjListCount(graph, u, NULL, 0);
	//printf("%d->%d\n",adjList[0],adjList[1]);
        //printf("%d\n",size);
	for (i=1;i<size;i++) 
        {
	    int v = adjList[i];
	    // printf("%d\n",v);   
            // If v is not yet included in MST and weight of u-v is
            // less than key value of v, then update key value and
            // parent of v
            if (isInMinHeap(minHeap, v) && findWeight(graph,u,v) < key[v])
            {
                key[v] = findWeight(graph,u,v);
                parent[v] = u;
                decreaseKey(minHeap, v, key[v]);
	    }
	 }
	 MSTWeight += minHeapNode->key;
    }
    int n;
    for (n=1;n<V;n++) {
       printf("Edge: %d -- %d (Weight: %d)\n",parent[n],n,key[n]);
    }
    printf("Total Weight: %d\n", MSTWeight);
    printf("===============================================\n");
}
Exemple #17
0
// 删除指定结点
bool deleteFromFibonaciHeap(FibonaciHeap *heap, FibonaciNode *node)
{
	decreaseKey(heap, node, FIBONACI_MINUS_INF);
	return extractMin(heap) == FIBONACI_MINUS_INF;
}
 int main()
{
	ElementType data[] = {85, 80, 40, 30, 10, 70, 110}; // P141	
	ElementType buildHeapData[] = {150, 80, 40, 30, 10, 70, 110, 100, 20, 90, 60, 50, 120, 140, 130};
	BinaryHeap bh;	
	int size;
	int i;	
	int capacity;
	
	printf("\n\t=== test for inserting the binary heap with {85, 80, 40, 30, 10, 70, 110} in turn ===\n");
	capacity = 14;
	bh = initBinaryHeap(capacity);
	size = 7;	
	
	
	for(i = 0; i < size; i++)
		insert(data[i], bh);
	printBinaryHeap(bh);

	printf("\n\t=== test for inserting the binary heap with {100, 20, 90} in turn ===\n");
	insert(100, bh);
	insert(20, bh);
	insert(90, bh);
	printBinaryHeap(bh);

	printf("\n\t=== test for inserting the binary heap with 5 ===\n");
	insert(5, bh);		
	printBinaryHeap(bh);

	printf("\n\t=== test for 3 deletings towards the minimum in binary heap ===\n");
	deleteMin(bh);	
	printBinaryHeap(bh);
	deleteMin(bh);		
	printBinaryHeap(bh);
	deleteMin(bh);	
	printBinaryHeap(bh);

	// other operations in bianry heap	
	printf("\n\t====== test for other operations in bianry heap as follows ======\n");
	printf("\n\t=== test for increaseKey(4, 120, bh) ===\n");
	increaseKey(4, 120, bh);
	printBinaryHeap(bh);
	
	printf("\n\t=== test for increaseKey(2, 120, bh) ===\n");
	increaseKey(2, 120, bh);
	printBinaryHeap(bh);

	printf("\n\t=== test for decreaseKey(9, 195, bh) ===\n");
	decreaseKey(9, 195, bh);
	printBinaryHeap(bh);

	printf("\n\t=== test for decreaseKey(4, 90, bh) ===\n");
	decreaseKey(4, 90, bh);
	printBinaryHeap(bh);
	

	printf("\n\t=== test for decreaseKey(7, 50, bh) ===\n");
	decreaseKey(7, 50, bh);
	printBinaryHeap(bh);
	
	printf("\n\t=== test for decreaseKey(5, 155, bh) ===\n");
	decreaseKey(5, 155, bh);
	printBinaryHeap(bh);



	printf("\n\t=== test for deleteElement(4, bh) ===\n");
	deleteElement(4, bh);
	printBinaryHeap(bh);

	printf("\n\t=== test for deleteElement(1, bh) ===\n");
	deleteElement(1, bh);
	printBinaryHeap(bh);

	
	printf("\n\t=== test for deleteElement(3, bh) ===\n");
	deleteElement(3, bh);
	printBinaryHeap(bh); // test over , Bingo!
	 
	// as you know, the build heap operation is identical with other operations
	printf("\n\t=== test for building heap with {150, 80, 40, 30, 10, 70, 110, 100, 20, 90, 60, 50, 120, 140, 130} ===\n");
	capacity = 16;
	bh = initBinaryHeap(capacity);
	bh->size = 15;
	bh->elements = buildHeapData; 
	buildHeap(bh);
	printBinaryHeapFromZero(bh);

	return 0;
}
Exemple #19
0
/*************************************************************************************
 * Function: userInputMode()
 * Description:	This is the function to handle User Input Mode
 * Return: 0-Success, 1-Unsucessful
 * Input: scheme - Fibonacci Heap or Leftist Tree, filePath - path of input file
 ************************************************************************************/
void userInputMode(char *scheme, char *filePath){	
	//struct f_node *f_root=NULL; //Root of Fibbonacci Heap pointer to Min tree
	//int operation, randomData; //To be used in Random Operation Generator
	FILE *inputFile; // User input File
	
	                                         	
	char operationUserInput[3] = {0}; //Operation in user input mode
	int userInputData, index, decreaseKeyBy; //Data in user input mode
	int fibonacciScheme, leftistScheme;

	inputFile = fopen(filePath, "r"); //Open input file in read mode

	if(strcmp(scheme, "-il") == 0){ //If scheme is Leftist Tree
		fibonacciScheme = 0;
		leftistScheme = 1;
	}
	else{ //If scheme is Fibonacci Heap
		fibonacciScheme = 1;
		leftistScheme = 0;
	}

		
		if(inputFile != NULL){ //If file is opened successfully
			if(log == DEBUG)
					printf("\nInitiating User mode Input...\n");
			
			while(strcmp(operationUserInput, "*") != 0){
				fscanf(inputFile, "%s", operationUserInput); //Scan first word
				
				//Delete Min Operation
				if(strcmp(operationUserInput, "D") == 0){
					if(fibonacciScheme){ //If it is fibonacci Scheme
						if(log == DEBUG)
							printf("\nDeleting Min of Fibonacci Heap....\n");
						MIN = deleteMin_MinFHeap(MIN);
					}
					else{ //If it is Leftist Tree
						if(log == DEBUG)
							printf("\nDeleting Min of Leftist Tree....\n");
						ROOT = deleteMinLeftistTree(ROOT);
					}
					
					
				}

				//Insert Operation
				else if(strcmp(operationUserInput, "I") == 0){
					fscanf(inputFile, "%d", &userInputData); //Read data

					if(fibonacciScheme){ //If it is fibonacci scheme
						if(log == DEBUG)
							printf("Inserting %d in Fibonacci Heap....\n", userInputData);
						MIN = insert_MinFHeap(MIN, userInputData);
					}
					else{ //If it is Leftist Tree
						if(log == DEBUG)
							printf("\nInserting %d in Leftist Tree....\n", userInputData);
						ROOT = insertMinLeftistTree(ROOT, userInputData);
					}
				}

				//Decrease Key
				else if(strcmp(operationUserInput, "DK") == 0){
					fscanf(inputFile, "%d", &index); //Read index
					fscanf(inputFile, "%d", &decreaseKeyBy); //Read decreasekeyby
					if(fibonacciScheme){
						if(log == DEBUG)
							printf("\nDecreasing Key of node at %d by %d....\n", index, decreaseKeyBy);
						MIN = decreaseKey(MIN, index, decreaseKeyBy);
					}
				}
				
				//Remove mode from Fibonacci Heap
				else if(strcmp(operationUserInput, "R") == 0){
					fscanf(inputFile, "%d", &index); //Read index

					if(log == DEBUG )
						printf("\nRemoving Key of node at %d....\n", index);
					MIN = removeMinFHeap(MIN, index);
				}
				
			}

			if(fibonacciScheme){
				if(!print_MinFHeap(MIN))
					printf("There was some problem in printing nodes!! Please try once again\n");
			}
			else{
				if(!printNodes(ROOT))
					printf("There was some problem in printing nodes!! Please try once again\n");
			}
		}

		else{
			if(log == DEBUG || log == INFO)
				printf("Sorry, File is not accessible!\n");
		}
	
}