#include "stdio.h"
#include "stdlib.h"
//上滤,下滤,指空穴的移动方向.
//另,二叉堆有堆序性,即父亲的权值始终小于每个儿子的权值。所以顶端是Min.
#define Element int
#define MinDATA -1
//MinData is first of Array.
//This MinDATA support a kindof heap which every num is bigger than zero.
struct node;
typedef struct node *Two_Heap;
struct node
{
int capacity;
int size;
int *Array;
};
Two_Heap InitHeap(int Maxsize);//if not space,return 0;
void Destroy(Two_Heap H);
void MakeEmpty(Two_Heap H);
void Insert(Element X,Two_Heap H);
Element DeleteMin(Two_Heap H);
Element FindMin(Two_Heap H);
int IsEmpty(Two_Heap H);//if empty,return 0;
int IsFull(Two_Heap H);//if full,return 0;
Two_Heap InitHeap(int Maxsize)//if not space,return 0;
{
Two_Heap H;
H=(Two_Heap)malloc(sizeof(struct node));
if(H==NULL)
{
printf("no space!\n");
return 0;
}
H->Array=(int*)malloc(sizeof(int)*Maxsize+1);
if(H->Array==NULL)
{
printf("no space!\n");
return 0;
}
H->capacity=Maxsize;
H->size=0;
H->Array[0]=MinDATA;//signal to end insert's "for"
return H;
}
void Destroy(Two_Heap H)
{
while(IsEmpty(H)!=0)//not empty
{
free(H->Array);
free(H);
}
}
void Insert(Element X,Two_Heap H)//上滤
{
int i;
if(IsFull(H)==0)//has been full
{
printf("This Two_Heap has been full.\n");
}
else
{
for(i=++H->size;H->Array[i/2]>X;i/=2)//that"++H->size" make points from one space.
H->Array[i]=H->Array[i/2];//every father instead child,and insteaded X.
//down to up,and every child instead of it's father.
//child to father
//and "H->size has been ++ in shadow."
H->Array[i]=X;
}
}
Element DeleteMin(Two_Heap H)//下滤
{
int i,child;
Element MinElement,LastElement;
//why have LastElement?
//MinElement to save array[1],because array[1] will be change,
//LastElement is "people" who we should move to right space.
if(IsEmpty(H)==0)
{
printf("No space can be delete,it's empty!\n");
return H->Array[0];
}
MinElement=H->Array[1];
LastElement=H->Array[H->size--];
for(i=1;i*2<=H->size;i=child)
{
child=i*2;//father to child
if(child!=H->size && H->Array[child+1]<H->Array[child])
child++;
//find smaller child.
if(LastElement>H->Array[child])
H->Array[i]=H->Array[child];
else
break;
}
H->Array[i]=LastElement;//find right space.
return MinElement;
}
Element FindMin(Two_Heap H)
{
return H->Array[1];
}
Element IsEmpty(Two_Heap H)
{
if(H->size==0)
return 0;
else
return 1;
}
Element IsFull(Two_Heap H)
{
if(H->size==H->capacity)
return 0;
else
return 1;
}
//this not all,Two_Heap also support some fuction.
//like:
//*DecreaseKey*
//*IncreaseKey*
//*Delete*
//*BuildHeap*
int main()
{
Two_Heap H;
int maxsize;
scanf("%d",&maxsize);
H=InitHeap(maxsize);
int i;
int temp;
for(i=0;i<maxsize;i++)
{
scanf("%d",&temp);
Insert(temp,H);
}
int min1,min2;
min1=FindMin(H);
DeleteMin(H);
min2=FindMin(H);
printf("%d %d\n",min1,min2);
Destroy(H);
return 0;
}
二叉堆
最新推荐文章于 2024-05-30 09:15:00 发布