#include<stdio.h>
#include<stdlib.h>
struct heap{
int *data;
int maxlenth,lenth;
};
struct heap*Creat(int MaxLenth){//lenth为下标,当前为0 当输入数据后,下标为最后一个元素的下标
struct heap*p;
p=(struct heap*)malloc(sizeof(struct heap));
p->maxlenth=MaxLenth;
p->lenth=0;
p->data=(int *)malloc(MaxLenth*sizeof(int) );
p->data[0]=100000;
return p;
}
void paixu(struct heap*maxheap){
int father,child,i;
int temp=maxheap->data[maxheap->lenth];
i=child=maxheap->lenth;
father=child/2;
for(;father>=1;){
if(temp<maxheap->data[father]){
maxheap->data[child]=maxheap->data[father];
i=child=father;
father=child/2;
}
else
break;
}
maxheap->data[i]=temp;
}
void print(struct heap*maxheap,int n){
printf("%d",maxheap->data[n]);
for(n/=2;n>=1;n/=2)
printf(" %d",maxheap->data[n]);
printf("\n");
}
int main(){
int N,i,M,n;
struct heap *maxheap;//最大堆
scanf("%d",&N);
scanf("%d",&M);
maxheap=Creat(N+1);
for(i=1;i<=N;i++){
scanf("%d",&maxheap->data[++maxheap->lenth]);
paixu(maxheap);
}
for(i=0;i<M;i++){
scanf("%d",&n);
print(maxheap,n);
}
return 0;
}
其中用maxheap注释了最小堆,是因为题目原因,懒得修改,实际上是最小堆的算法,转换成最大堆无非是改一下判断符号 影响不大。