This is a question from oj PAT
Insert a sequence of given numbers into an initially empty min-heap H. Then for any given index i, you are supposed to print the path from H[i] to the root.
However, my code always time out, i.e, it takes too long time. How to solve it?
main()
{
int i,*a,n,m,k,data;
scanf("%d%d",&n,&m);
a=malloc(n*sizeof(int));
a[0]=-10001; //
for(i=1;i<=n;i++)
{
scanf("%d",&data);
heapAdjust(a,data);
}
for(i=1;i<=m;i++)
{
scanf("%d",&k);
printf("%d",a[k]);
k=k/2;
while(1)
{
printf(" %d",a[k]);
if(k==1)
break;
k=k/2;
}
printf("\n");
}
free(a);
}
void heapAdjust(int a[],int data) // make heap
{
static int size=0;
int i;
i=++size;
for(;a[i/2]>data;i=i/2)
a[i]=a[i/2];
a[i]=data;
}