[PTA] Percolate Up and Down

#include <stdio.h>
#include <stdlib.h>

typedef int ElementType;
#define MinData -1

typedef struct HeapStruct *PriorityQueue;
struct HeapStruct {
    ElementType  *Elements;
    int Capacity;
    int Size;
};

PriorityQueue Initialize( int MaxElements ); /* details omitted */

void PercolateUp( int p, PriorityQueue H );
void PercolateDown( int p, PriorityQueue H );

void Insert( ElementType X, PriorityQueue H ) 
{
    int p = ++H->Size;
    H->Elements[p] = X;
    PercolateUp( p, H );
}

ElementType DeleteMin( PriorityQueue H ) 
{ 
    ElementType MinElement; 
    MinElement = H->Elements[1];
    H->Elements[1] = H->Elements[H->Size--];
    PercolateDown( 1, H );
    return MinElement; 
}

PriorityQueue Initialize( int MaxElements )
{
	PriorityQueue p;
	p=(PriorityQueue)malloc(sizeof(struct HeapStruct));
	p->Elements=(int*)malloc(sizeof(int)*MaxElements);
	p->Capacity=MaxElements;
	p->Size=0;
	p->Elements[0]= MinData;
	return p;
}

void PercolateUp( int p, PriorityQueue H )
{
	int tmp=H->Elements[p];
	for(;H->Elements[p/2]>tmp;p/=2){
		H->Elements[p]=H->Elements[p/2];
	}
	H->Elements[p]=tmp;
}

void PercolateDown( int p, PriorityQueue H )
{
	int child;
	int tmp=H->Elements[1];
	for(;2*p<H->Size;p=child){
		child=2*p;
		if(child!=H->Size-1&&H->Elements[child+1]<H->Elements[child]){
			child++;
		}
		if(H->Elements[child]<tmp)H->Elements[p]=H->Elements[child];
		else break;
	}
	H->Elements[p]=tmp;
}

int main()
{
    int n, i, op, X;
    PriorityQueue H;

    scanf("%d", &n);
    H = Initialize(n);
    for ( i=0; i<n; i++ ) {
        scanf("%d", &op);
        switch( op ) {
        case 1:
            scanf("%d", &X);
            Insert(X, H);
            break;
        case 0:
            printf("%d ", DeleteMin(H));
            break;
        }
    }
    printf("\nInside H:");
    for ( i=1; i<=H->Size; i++ )
        printf(" %d", H->Elements[i]);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值