Beispiel #1
0
main( )
{
    BinQueue H;
    int i, j;
    ElementType AnItem;

    H = Initialize( );
    for( i=0, j=MaxSize/2; i<MaxSize; i++, j=( j+71)%MaxSize )
    {
      printf( "Inserting %d\n", j );
      H = Insert( j, H );
    }
 #if 1
    j = 0;
    while( !IsEmpty( H ) )
    {
      printf( "DeleteMin\n" );
      H = DeleteMin( &AnItem, H );
      if( DeleteMin( H ) != j++ )
            printf( "Error in DeleteMin, %d\n", j );
    }
    if( j != MaxSize )
        printf( "Error in counting\n" );
    #endif
    printf( "Done...\n" );
    return 0;
}
Beispiel #2
0
void Tester::FHeapDecreaseKeyBig(const unsigned int times) {
	auto fheap = std::make_shared<FHeap>();    
    for(unsigned i = 0; i < times + 1; ++i) {
        fheap->Insert(i+2,i+2);
    }
	fheap->DeleteMin();

	Timer t;
	unsigned int comparisons = 0;
    for(unsigned i = times + 1; i < REPS + times + 1; ++i) {
        
		std::shared_ptr<INode> node = fheap->Insert(i+2,i+2);
		fheap->DeleteMin();

		fheap->comparisons = 0;
		
		t.start();
		fheap->DecreaseKey(node, i + 1);
		t.stop();
		comparisons += fheap->comparisons;

		fheap->DeleteMin();
    }

    std::cout << "N: \t" << times << "\t" << t.duration().count() <<  " ms\t" << comparisons << " comparisons" << std::endl;
}  
Beispiel #3
0
void Tester::FHeapDecreaseKeySmall(const unsigned int times) {
	auto fheap = std::make_shared<BHeap>();    
    for(unsigned i = times + REPS + 1; i > REPS + 1; --i) {
        fheap->Insert(i+2,i+2);
    }
	fheap->DeleteMin();

	Timer t;
	std::shared_ptr<INode> node;
	unsigned int comparisons = 0;

    for(unsigned i = REPS; i > 0; --i) {
		node = fheap->Insert(i, i);
		node = fheap->Insert(i+1, RAN_NUMS.at(i));
		fheap->DeleteMin();

		fheap->comparisons = 0;
      
		t.start();
		fheap->DecreaseKey(node, i + 1);
		t.stop();

		comparisons += fheap->comparisons;
		fheap->DeleteMin();
		
		
	}

    std::cout << "N: \t" << times << "\t" << t.duration().count() <<  " ms\t" << comparisons << " comparisons" << std::endl;
}
Beispiel #4
0
 Node<Key, Val>* DeleteInternal(Node<Key, Val>* h, Key key){
   if (h == NULL) return NULL;
   if (Comp()(key, h->key)){
     if (!IsRED(h->left) && 
         h->left != NULL &&
         !IsRED(h->left->left)){
       h = MoveREDLeft(h);
     }
     h->left = DeleteInternal(h->left, key);
   } else {
     if (IsRED(h->left)){
       h = RotateRight(h);
     }
     if ((key == h->key) && (h->right == NULL)){
       return NULL;
     }
     if (!IsRED(h->right) && 
         h->right != NULL && 
         !IsRED(h->right->left)){
       h = MoveREDRight(h);
     }
     if (key == h->key){
       Node<Key, Val>* min_node = GetMin(h->right);
       h->key = min_node->key;
       h->val = min_node->val;
       h->right = DeleteMin(h->right);
     } else {
       h->right = DeleteInternal(h->right, key);
     }
   }
   return FixUp(h);
 }
Beispiel #5
0
BSTree Delete(ElementType x, BSTree tr)
{
	if(tr == NULL)
		return NULL;

	if(x < tr->elem)
		tr->left = Delete(x, tr->left);
	else if(x > tr->elem)
		tr->right = Delete(x, tr->right);
	else
	{
		if(tr->left && tr->right)
		{
//			Position p = FindMin(tr->right);
//			tr->elem = p->elem;
//			tr->right = Delete(p->elem, tr->right);
			tr->elem = DeleteMin(tr->right); // this operation also can be down by the above 3 sentences;
		}
		else
		{
			Position temp = tr;
			if(tr->left == NULL)
				tr = tr->right;
			else if(tr->right == NULL)
				tr = tr->left;
			free(temp);
		}
	}

	return tr;
}
Beispiel #6
0
void Prim(Graph *g, TableInstance t, Index start)
{
    Node *v;

    PriorityQueue priorityQueue = Initialize(g->Size * 3);
    InitializeVertextQueue(priorityQueue, t, g->Cells.size());
    for(;;)
    {
        do{
            v = DeleteMin(priorityQueue).CurrentNode;
            if(v->InternalNumber == NotAVertex)
                break;
        }while(t[v->InternalNumber].Known);

        if(v->InternalNumber == NotAVertex)
            break;
        t[v->InternalNumber].Known = true;
        list<Node*>::iterator iter = g->Cells[v->InternalNumber - 1]->Children.begin();
        for(;iter != g->Cells[v->InternalNumber - 1]->Children.end(); iter ++)
        {
            if(!t[(*iter)->InternalNumber].Known)
            {
                if(t[(*iter)->InternalNumber].Distance > (*iter)->weight)
                {
                    t[(*iter)->InternalNumber].Distance = (*iter)->weight;
                    t[(*iter)->InternalNumber].ParentNode = v;
                    Insert(t[(*iter)->InternalNumber], priorityQueue);
                }
            }
        }
    }
    delete[] priorityQueue->Elements;
}
Beispiel #7
0
/*堆排序,直接调用了之前编写的二叉堆代码*/
void HeapSort(ElementType A[], int N)
{
	int i;
	PriorityQueue H = BuildHeap(A, N);
	for(i=0; i<N; i++)
		A[i] = DeleteMin(H);

	Destroy(H);
}
Beispiel #8
0
void Tester::FHeapDeleteMinSmall(const unsigned int times) {
	auto fheap = std::make_shared<FHeap>();    
    for(unsigned i = REPS + times + 1; i > REPS; --i) {
        fheap->Insert(i+2,i+2);
    }
	fheap->DeleteMin(); // To get a more interesting tree	

	unsigned int comparisons = 0;
	Timer t;
	for(unsigned i = REPS; i > 0; --i) {
		fheap->comparisons = 0;
		t.start();
		fheap->DeleteMin();
		t.stop();
		comparisons += fheap->comparisons;

		fheap->Insert(i+2, i+2);
    }
    std::cout << "N: \t" << times << "\t" << t.duration().count() <<  " ms\t" << comparisons << " comparisons" << std::endl;
}
Beispiel #9
0
Datei: ft.c Projekt: 8l/csolve
Vertices *
MST(Vertices * graph)
{
  HeapP * heap;
  Vertices * vertex;
  Edges * edge;
  ;

  InitFHeap();

  /*
   * key(s) = 0;
   * key(v) = infty for v != s;
   * init heap;
   * make a heap;
   * put s in heap;
   */
  vertex = graph;
  KEY(vertex) = 0;
  heap = MakeHeap();
  (void)Insert(&heap, (Item *)vertex);

  vertex = NEXT_VERTEX(vertex);
  while(vertex != graph)
  {
    KEY(vertex) = PLUS_INFINITY;
    vertex = NEXT_VERTEX(vertex);
  }
  while(vertex != graph);

  vertex = FindMin(heap);
  while(vertex != NULL_VERTEX)
  {
    heap = DeleteMin(heap);
    KEY(vertex) = MINUS_INFINITY;
    edge = EDGES(vertex);
    while(edge != NULL_EDGE)
    {
      if(WEIGHT(edge) < KEY(VERTEX(edge)))
      {
        KEY(VERTEX(edge)) = WEIGHT(edge);
        CHOSEN_EDGE(VERTEX(edge)) = edge;
        (void)Insert(&heap, VERTEX(edge));
      }
      edge = NEXT_EDGE(edge);
    }
    vertex = FindMin(heap);
  }
  ;
  return(graph);
}
Beispiel #10
0
void Topsort( Graph G, Table HT, int N )
{   /* 拓扑排序得到解并输出 */
    MinHeap Q = (MinHeap)malloc( sizeof( struct HeapStruct ) );
    HeapNode Tmp = (HeapNode)malloc( sizeof( struct HeapRecord ) );
    int  i, j, InDegree[MAXN];
    int flag = 0;

    /* 初始化最小堆 */
    Q->Elements = 
(HeapNode)malloc((G->NumVert+1)*sizeof(struct HeapRecord));
    Q->HeapSize = 0;
    Q->Elements[0].Num = -1;

    /* 计算初始入度,建立0入度结点的最小堆 */
    for ( i=0; i<G->NumVert; i++ ) {
        InDegree[i] = 0;
        if ( !(HT->T[i]<0) ) { /* 只对每个非空单元的元素计算入度 */
            for ( j=0; j<G->NumVert; j++ )
                InDegree[i] += G->M[j][i];
            if ( !InDegree[i] ){ /* 入度为0者存入最小堆 */
                Tmp->Index = i;  Tmp->Num = HT->T[i];
                InsertHeap( Tmp, Q );
            }
        }
    }

    /* 拓扑排序 */
    while ( Q->HeapSize ) {
        Tmp = DeleteMin( Q ); /* 输出当前数值最小的入度为0的元 */
        if ( flag )
            printf(" %d", Tmp->Num); /* 输出其它元素,元素前有空格*/
        else {
            printf("%d", Tmp->Num); /* 输出第1个元素,元素前没有空格*/
            flag = 1;
        }
        /* 将该结点从图中删去 */
        i = Tmp->Index;
        for (j=0; j<G->NumVert; j++ ) {
            if ( G->M[i][j] ) {
                InDegree[j]--;
                if ( !InDegree[j] ) {  /* 更新后入度为0者存入最小堆 */
                    Tmp->Index = j;  Tmp->Num = HT->T[j];
                    InsertHeap( Tmp, Q );
                }
            }
        }
    }
    printf("\n");
}
Beispiel #11
0
 Node<Key, Val>* DeleteMin(Node<Key, Val>* h){
   if (h->left == NULL){
     return NULL;
   }
   if (!IsRED(h->left) && !IsRED(h->left->left)){
     h = MoveREDLeft(h);
   }
   Node<Key, Val>* new_left = DeleteMin(h->left);
   if (new_left == NULL){
     --num_;
     delete h->left;
   }
   h->left = new_left;
   return FixUp(h);
 }
Beispiel #12
0
main( )
{
    PriorityQueue H;
    int i, j;

    H = Initialize( MaxSize );
    for( i=0, j=MaxSize/2; i<MaxSize; i++, j=( j+71)%MaxSize )
        Insert( j, H );

    j = 0;
    while( !IsEmpty( H ) )
        if( DeleteMin( H ) != j++ )
            printf( "Error in DeleteMin, %d\n", j );
    printf( "Done...\n" );
    return 0;
}
Beispiel #13
0
void KruskalALG(ALGraph * G){
	char v;
	int i,j,k,parent1,parent2,EdgeNum;
	EdgeNode * edge;
	SetType S[G->n];
	MinHeap H;
	H = (MinHeap)CreateMinHeap();
	int Visited[G->n];
	
	// Initialization
	for(i=0; i<G->n; i++){
		S[i].Data = G->Adjlist[i].Vertex;	//将所有的顶点存入生成树的集合 
		S[i].Parent = -1;					//一开始所有顶点都是一棵独立的树 
		Visited[i] = FALSE;
		edge = G->Adjlist[i].FirstEdge;
		while( edge ){						//将所有的边组成一个最小堆(越上面的元素值越小) 
			MinHeapInsert(H,edge);
			edge = edge->Next;
		}
	}
	
	EdgeNum = 0;
	while( EdgeNum < (G->n) || !IsEmptyMin(H) ){
	//为什么不是找到n-1条边就停下:因为按目前的写法边数的增加次数和点的输出次数保持一致
	//要输出n个点,EdgeNum就必须++ n次【需改进】 
		edge = (EdgeNode*)DeleteMin(H);
		parent1 = SetFind(S,G->n,edge->Vertex);
		parent2 = SetFind(S,G->n,edge->AdjV);
		if( parent1!=parent2 || parent1==-1 ){
			if( !Visited[edge->Vertex] ) {
				printf("Visited Vertex : %c \n",S[edge->Vertex]);
				Visited[edge->Vertex] = TRUE;
				EdgeNum++;
			}
			if( !Visited[edge->AdjV] ) {
				printf("Visited Vertex : %c \n",S[edge->AdjV]);
				Visited[edge->AdjV] = TRUE;
				EdgeNum++;
			}
			SetUnion(S,G->n,edge->Vertex,edge->AdjV);
		}
	}
	if( EdgeNum < G->n ) printf("图不连通\n");
	
	return ;
}
Beispiel #14
0
Datei: heap.c Projekt: saitej3/CN
int main()
{
        int number_of_elements;
        scanf("%d",&number_of_elements);
        int iter, element;
        Init();
        for(iter = 0;iter < number_of_elements;iter++)
        {
                scanf("%d",&element);
                Insert(element);
        }
        for(iter = 0;iter < number_of_elements;iter++)
        {
                printf("%d ",DeleteMin());
        }
        printf("\n");
        return 0;
}
Beispiel #15
0
void main() {
    PriorityQueue H = Init(15, -1);
    Insert(13, H);
    Insert(21, H);
    Insert(16, H);
    Insert(24, H);
    Insert(31, H);
    Insert(19, H);
    Insert(68, H);
    Insert(65, H);
    Insert(26, H);
    Insert(32, H);
    Insert(14, H);
    PrintPriorityQueue(H);
    printf("Will delete: %d\n", DeleteMin(H));
    printf("cruuent Min is: %d\n", FindMin(H));
    PrintPriorityQueue(H);
    Destory(H);
    
}
Beispiel #16
0
void Tester::BHeapDeleteMinSmall(const unsigned int times) {
	auto bheap = std::make_shared<BHeap>();    
    for(unsigned i = times; i > 0; --i) {
        bheap->Insert(i+2,i+2);
    }

	Timer t;
	unsigned int comparisons = 0;
	for(unsigned i = 0; i < REPS; ++i) {
		bheap->comparisons = 0;
		t.start();
		bheap->DeleteMin();
		t.stop();
		comparisons += bheap->comparisons;

		bheap->Insert(i+2, i+2);
    }

    std::cout << "N: \t" << times << "\t" << t.duration().count() <<  " ms\t" << comparisons << " comparisons" << std::endl;
}
Beispiel #17
0
int main()
{
	PriorityQueue H;
	H = Initialize(60);
	printf("Min element %d",H->Elements[0]);
	printf("\n");


	int i;
	for(i=0; i<30; i++)
		Insert(i*2, H);

	for(i=30; i>=0; i--)
		Insert(i*2-1, H);

	for(i=0;i<15; i++)
		printf("%d  ",DeleteMin(H));

	printf("\n");
	printBHeap(H, 0, 1);
	printf("\n");

}
Beispiel #18
0
void Kruskal(Graph *g, TableInstance t, list<Edge> &edgeList)
{
    Node *v;
    int edgeAccepted = 0;
    DisjSet disjSet = new SetType[g->Cells.size()];

    InitializeDisjSet(disjSet, g->Cells.size());
    PriorityQueue priorityQueue = Initialize(g->Size * 3);
    InitializeVertextQueue(priorityQueue, t, g->EdgeNumber);
    while(edgeAccepted < g->Cells.size() - 1)
    {
        Table edge = DeleteMin(priorityQueue);
        SetType set1 = FindInDisjSet(edge.CurrentNode->InternalNumber, disjSet);
        SetType set2 = FindInDisjSet(edge.ParentNode->InternalNumber, disjSet);
        if(set1 != set2)
        {
            SetUnion(disjSet, set1, set2);
            edgeList.push_back(Edge{edge.CurrentNode->RealName, edge.ParentNode->RealName, edge.Distance});
            edgeAccepted ++;
        }
    }
    delete[] disjSet;
}
Beispiel #19
0
int main(){
    srand((unsigned)time(NULL));
    PriorityQueue H = Initialize(15);
    int choice;
    int item;
    int i;

    instructions();
    printf("your choice:");
    scanf("%d",&choice);

    while(choice != 3){
        switch(choice){
            case 1:
                for(i = 0;i < H->Capacity;i++){
                    Insert(rand()%101,H);
                }
                printf("%d\n",H->Capacity);
                printf("%d\n",H->Size);
                printHeap(H);
                break;
            case 2:
                DeleteMin(H);
                printHeap(H);
                break;
            default:
                printf("\nInvalid choice\n");
                instructions();
        }
        printf("\nyour choice:");
        scanf("%d",&choice);
    }
    Destroy(H);
    printf("\nrun to end\n");

    return 0;
}
Beispiel #20
0
void Kruskal(Graph G)
{
	int EdgesAccepted;
	DisjSet S;
	PriorityQueue H;
	Vertex U, V;
	SetType Uset, Vset;
	Edge E;

	Initialize(S);
	ReadGraphIntoHeapArray(G, H);
	BuildHeap(H);

	EdgesAccepted = 0;
	while (EdgesAccepted < NumVertex - 1) {
		E = DeleteMin(H);
		Uset = Find(U, S);
		Vset = Find(V, S);
		if (Uset != Vset) {
			EdgesAccepted++;
			SetUion(S, USet, VSet);
		}
	}
}
Beispiel #21
0
void
PairHeap<Etype>::DeleteMin( )
{
    static Etype Ignored;    // To avoid repeated constructions
    DeleteMin( Ignored );
}
Beispiel #22
0
 void fibonacci_heap::pop() {
   DeleteMin();
 }
Beispiel #23
0
int main() {

	/* Question 1. */
	puts(KBLU "\n1. Read in numbers in data 100 one by one and insert them into an initially empty heap. Print out the elements in the array (you should check the output to see if the heap order is satisfied)." RESET);

	// open file
	FILE * fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts(KRED "ERROR: Failed to open file." RESET);
		exit(-1);
	}
	// create binary heap
	PriorityQueue H = Initialize( 100 );
	// insert data
	int i, cur;
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Insert(cur, H);
	}

	// print data in order
	PrintHeap( H );
	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );


	/* Question 2. */
	puts(KBLU "\n2. Write a function to print out elements that are smaller than 15000 (not necessary in sorted order). The function should run in O(K), where K is the number of the elements you print out. " RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize( 100 );
	// insert data
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Insert(cur, H);
	}

	// print data in order
	PrintSmaller( 15000, H );
	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* Question 3. */
	puts(KBLU "\n3. Read in numbers in data 100 into an array. Implement BuildHeap and use it to convert the array into a heap.\n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize( 100 );
	// insert data
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}

	// random array
	puts("before:"); PrintHeap( H );
	// build heap
	BuildHeap( H );
	// print the heap
	puts("\nafter:"); PrintHeap( H );

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* Question 4. */
	puts(KBLU "\n4. Find the 30th smallest element by repeatly using DeleteMin. \n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize( 100 );
	// build heap
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}
	BuildHeap( H );

	// first 30 smallest number
	int tmp;

	for ( i = 0; i < 30; ++i ) 
	{
		tmp = DeleteMin( H );
		printf("%d ", tmp);
	}
	printf("\n\n\t30th smallest number is" KYEL " %d\n" RESET, tmp);

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* Question 5. */
	puts(KBLU "\n5. Implement Algorithm 6B and use it to find the 71st largest element in file data 100. \n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize( 100 );
	// build heap
	for ( i = 0; i < 71; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}
	BuildHeap( H );
	// replace the smallest element
	for ( i = 71; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		if ( cur > FindMin( H ) )
		{
			DeleteMin( H );
			Insert( cur, H );
		}
	}
	printf("\t71st largest number is" KYEL " %d\n" RESET, FindMin( H ));

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* EXPERIMENT */
	puts(KBLU "\n6. Read in numbers in data 100 into an array. Implement BuildHeap and use it to convert the array into a 4-heap.\n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts("ERROR: Failed to open file.");
		exit(-1);
	}
	// create binary heap
	H = Initialize4Heap( 100 );
	// build heap
	for ( i = 0; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}

	// random array
	puts("before:"); PrintHeap( H );
	// build heap
	BuildHeap( H );
	// print the heap
	puts("\nafter:"); PrintHeap( H );

	/* Question 7. */
	puts(KBLU "\n7. Find the 30th smallest element by repeatly using DeleteMin. (4-heap)\n" RESET);

	// first 30 smallest number
	for ( i = 0; i < 30; ++i ) 
	{
		tmp = DeleteMin( H );
		printf("%d ", tmp);
	}
	printf("\n\n\t30th smallest number is" KYEL " %d\n" RESET, tmp);

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	/* Question 8. */
	puts(KBLU "\n8. Implement Algorithm 6B and use it to find the 71st largest element in file data 100. (4-heap)\n" RESET);

	// open file
	fp = fopen(DATA100, "rb+");
	if (!fp) 
	{
		puts(KRED "ERROR: Failed to open file." RESET);
		exit(-1);
	}
	// create binary heap
	H = Initialize4Heap( 100 );
	// build heap
	for ( i = 0; i < 71; ++i )
	{
		fscanf(fp, "%d", &cur);
		Append(cur, H);
	}
	BuildHeap( H );
	// replace the smallest element
	for ( i = 71; i < 100; ++i )
	{
		fscanf(fp, "%d", &cur);
		if ( cur > FindMin( H ) )
		{
			DeleteMin( H );
			Append( cur, H );
			BuildHeap( H );
		}
	}
	printf("\t71st largest number is" KYEL " %d\n" RESET, FindMin( H ));
	puts("");

	// empty the heap
	MakeEmpty( H );
	// destroy the heap
	Destroy( H );

	return 0;
}
int main()
{
        int graph[maxVertices][maxVertices],size[maxVertices]={0},distance[maxVertices]={0},cost[maxVertices][maxVertices];
        int vertices,edges,weight;
        int iter;
        /* vertices represent number of vertices and edges represent number of edges in the graph. */
        scanf("%d%d",&vertices,&edges);
        int from,to;
        for(iter=0;iter<edges;iter++)
        {
                scanf("%d%d%d",&from,&to,&weight);
                assert(from>=0 && from<vertices);
                assert(to>=0 && to<vertices);
                graph[from][size[from]] = to;
                cost[from][size[from]] = weight;
                size[from]++;
        }
        int source;
        scanf("%d",&source);
        Node temp;
        for(iter=0;iter<vertices;iter++)
        {
                if(iter==source)
                {
                        temp.distance = 0;
                        distance[0]=0;
                }
                else
                {
                        temp.distance = infinity;
                        distance[iter]= infinity;
                }
                temp.vertex = iter;
                Insert(temp);
        }
        while(heapSize)
        {
                Node min = DeleteMin();
                int presentVertex = min.vertex;
                if(seen[presentVertex])
                {
                        /* This has already been processed */
                        continue;
                }
                seen[presentVertex] = 1;
                for(iter=0;iter<size[presentVertex];iter++)
                {
                        int to = graph[presentVertex][iter];
                        if(distance[to] > distance[presentVertex] + cost[presentVertex][iter])
                        {
                                distance[to] = distance[presentVertex] + cost[presentVertex][iter];
                                /* Instead of updating it in the queue, insert it again. This works because the updated
                                   distance is less than previous distance which makes it to pop out of the queue early */
                                temp.vertex = to;
                                temp.distance = distance[to];
                                Insert(temp);
                        }
                }
        }
        for(iter=0;iter<vertices;iter++)
        {
                printf("vertex is %d, its distance is %d\n",iter,distance[iter]);
        }


        return 0;



}
Beispiel #25
0
int main()
{
	int t,l;
	int k;
	char a[100],b[100];
	char c[100];
	scanf("%lld",&t);
	
	while(t--)
	{
		scanf("%s",c);
		if(strcmp("InitHeap",c)==0)
		{
			hsize++;
			scanf("%s",a);
			scanf("%s",b);
			strcpy(h[hsize].first,a);
			strcpy(h[hsize].last,b);
			h[hsize].arrpos=hsize;
			percolateUp(hsize);
			}
		else if(strcmp("Insert",c)==0)
		{
			hsize++;
			scanf("%s",a);
			scanf("%s",b);
			strcpy(h[hsize].first,a);
			strcpy(h[hsize].last,b);
			h[hsize].arrpos=hsize;
			percolateUp(hsize);
			k=find(a,b);
			printf("%d\n",k);
		}
		else if(strcmp("FindMin",c)==0)
		{	
			if(hsize>=1)
			printf("%s %s\n",h[1].first,h[1].last);
			else
			printf("-1\n");		
		}
		else if(strcmp("DeleteMin",c)==0)
		{
			if(hsize<1)
				printf("-1\n");
			else
			{
				printf("%s %s\n",h[1].first,h[1].last);
				DeleteMin();
			}
		}
		else if(strcmp("Delete",c)==0)
		{
			scanf("%lld",&l);
			if(l==0)
			printf("-1\n");
			else if(hsize<l)  
			printf("-1\n");
			else
			{	
				printf("%s %s\n",h[l].first,h[l].last);
				deletepos(l);
			}
		}
	}
	return 0;
}
Beispiel #26
0
int main(){
	int amount,i,j,k,m,n,weight[MAXSIZE];
	HuffmanTree HT;
	char data;
	MinHeap H = CreateMinHeap();
	
	scanf("%d",&amount);
	for(i=0;i<amount;i++){
		do{
			data = getchar();
		}while( data=='\n' || data==' ' );
		scanf("%d",&weight[i]);
		HT = (HuffmanTree)malloc(sizeof(struct HuffmanTreeNode));
		HT->Deepth=0;
		HT->Data = data;
		HT->Weight = weight[i];
		HT->Left = HT->Right = NULL;
		MinHeapInsert(H,HT);
	}
	
	while( H->Size>1 ){			//总共做 H->Size - 1 次合并(用for循环?) 
		HuffmanTree HT = (HuffmanTree)malloc(sizeof(struct HuffmanTreeNode));
		HT->Deepth = 0;
		HT->Data = '?';
		HT->Left = DeleteMin(H);
//		printf("HT->Left:%c :Deepth=%d ,Weight=%d \n",HT->Left->Data,HT->Left->Deepth,HT->Left->Weight);
		HT->Left->Deepth++;
		HT->Right = DeleteMin(H);
//		printf("HT->Right:%c :Deepth=%d ,Weight=%d \n",HT->Right->Data,HT->Right->Deepth,HT->Right->Weight);
		HT->Right->Deepth++;   
		HT->Weight = HT->Left->Weight + HT->Right->Weight;
		H = MinHeapInsert(H,HT);   
	}
//	HT  = Huffman(H);
	HT = DeleteMin(H);
//	HuffmanLevelPrint(HT);
	
	// Identify the answer //
	int wpl = WPL(HT);
	int repeat,answer,isPrefix;
	char *str[amount];
	char *temp;
	scanf("%d",&repeat);
	for(i=0;i<repeat;i++){
		answer = 0;
		for(j=0;j<amount;j++){
			do{
			   data = getchar();
			}while( data=='\n' || data==' ' );
			str[j] = (char*)malloc(sizeof(char)*amount);
			scanf("%s",str[j]);
			answer+= weight[j]*strlen(str[j]);
		}
		// Check the prefix
  		// 1.sort out ,front to rear,small to large
		for(k=1;k<amount;k++){
			for(m=0;m<amount-k;m++){
				if( strlen(str[m]) > strlen(str[m+1]) ){
					temp = str[m];
					str[m] = str[m+1];
					str[m+1] = temp;	
				}
			} 
		} 
		// 2.compare the prefix
		isPrefix = 0;
		for(k=0;k<amount;k++){
			for(m=k+1;m<amount;m++){
				for(n=0;str[k][n]!='\0';n++){
					if( str[k][n]!=str[m][n] )
						break;
				}
				if( str[k][n]=='\0' ){
					isPrefix = 1;
					k = amount;
					break;
				}
			}
		}
		if( answer==wpl && !isPrefix ){
			printf("Yes\n");
		}else{
			printf("No\n");
		}
	}
	

////////////////////////////////////////////////////////////////////////// 
	printf("\nInput a number to close the Console:\n");
	scanf("%d",&i);
	return 0;
}