5 3
46 23 26 24 10
5 4 3
1.代码
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 1000
typedef int ElementType;
typedef struct HNode *Heap;
struct HNode {
ElementType *Data;
int Size;
int Capacity;
};
typedef Heap MinHeap;
#define MINDATA -20000
MinHeap CreateHeap( int MinSize )
{
MinHeap H = (MinHeap)malloc(sizeof(struct HNode));
H->Data = (ElementType *)malloc((MinSize+1)*sizeof(ElementType));
H->Size = 0;
H->Capacity = MinSize;
H->Data[0] = MINDATA;
return H;
}
int Insert( MinHeap H, ElementType X )
{
int i;
if (H->Size == H->Capacity) {
printf("最小堆已满");
return -1;
}
i = ++H->Size;
for ( ; H->Data[i/2] > X; i/=2 )
H->Data[i] = H->Data[i/2];
H->Data[i] = X;
return 1;
}
void PercDown( MinHeap H, int p )
{
int Parent, Child;
ElementType X;
X = H->Data[p];
for( Parent=p; Parent*2<=H->Size; Parent=Child ) {
Child = Parent * 2;
if( (Child!=H->Size) && (H->Data[Child]>H->Data[Child+1]) )
Child++;
if( X <= H->Data[Child] ) break;
else
H->Data[Parent] = H->Data[Child];
}
H->Data[Parent] = X;
}
void BuildHeap( MinHeap H )
{
int i;
for( i = H->Size/2; i>0; i-- )
PercDown( H, i );
}
int main(){
int i, t, N, M;
int X;
int a[MaxSize];
scanf("%d", &N);
scanf("%d", &M);
MinHeap H = CreateHeap(N);
for(i=1; i<=N; i++){
scanf("%d", &X);
Insert(H, X);
}
for(i=0; i<M; i++)
scanf("%d", &a[i]);
for(i=0; i<M; i++){
t = a[i];
printf("%d", H->Data[t]);
for(t=t/2; t>0; t/=2)
printf(" %d", H->Data[t]);
printf("\n");
}
return 0;
}
2.小结
- 注意审题
数字间以1个空格分隔,行末不得有多余空格。
for(i=0; i<M; i++){
t = a[i];
printf("%d", H->Data[t]);
for(t=t/2; t>0; t/=2)
printf(" %d", H->Data[t]);
printf("\n");
}