#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
#define HEAP_INIT_SIZE 100
typedef struct {
ElemType *elem;//elem[0]不用
int hlength;
int heapsize;
}Heap;
Status InitHeap(Heap *H){//初始化堆
H->elem=(ElemType*)malloc(HEAP_INIT_SIZE*sizeof(ElemType));
if(!H->elem)
exit(OVERFLOW);
H->hlength=0;
H->heapsize=HEAP_INIT_SIZE;
return OK;
}
Status down(Heap *H,int pos){//向下调整
int i;
ElemType rc=H->elem[pos];
for(i=2*pos;i<=H->hlength;i*=2){
if(i<H->hlength&&compare(H->elem[i],H->elem[i+1])>0)
i++;
if(compare(H->elem[i],rc)>=0)
break;
H->elem[pos]=H->elem[i];
pos=i;
}
H->elem[pos]=rc;
return OK;
}
Status MakeMinHeap(Heap *H){//创建最小堆
int i;
for(i=H->hlength/2;i>0;i--)
down(H,i);
return OK;
}
ElemType DeleteMin(Heap *H){//删除最小元素并返回
ElemType r=H->elem[1];
H->elem[1]=H->elem[H->hlength--];
down(H,1);
return r;
}
Status up(Heap *H,int pos){//向上调整
ElemType r=H->elem[pos];
int q=pos/2;
while(q>=1&&compare(r,H->elem[q])<0){
H->elem[pos]=H->elem[q];
pos=q;
q=pos/2;
}
H->elem[pos]=r;
return OK;
}
Status insert(Heap *H,ElemType e){//插入元素
H->elem[++H->hlength]=e;
up(H,H->hlength);
return OK;
}
Status ChangeKey(Heap *H,int pos,ElemType e){//改变pos处的优先级
if(compare(H->elem[pos],e)<0){
H->elem[pos]=e;
down(H,pos);
}
else{
H->elem[pos]=e;
up(H,pos);
}
return OK;
}
堆
最新推荐文章于 2024-03-16 14:29:04 发布