0

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;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
TIMFUNNY
  • 363
  • 4
  • 9
  • 26

1 Answers1

1

You are probably running into an infinite loop because k becomes zero at some point.

Try changing the break condition inside the while(1) loop from k == 1 to k <= 1 and see if that helps.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    In fact, `k` will go to 0 if the input is `1` (i.e. they ask for the path from the root). Easily solved if you replace that `while(1)` with a `while(k > 0)`. Simplifies the code, too. – Jim Mischel May 25 '15 at 13:59