7-9 Paths in the Heap (25 points)

Inserts a series of given numbers into a small top heap that is initially empty H[]. Then for any given subscript i, print H[i]the path from to the root node.

Input format:

The first line of each set of tests contains two positive integers N and M ( 1 0 0 0), which are the number of inserted elements and the number of paths to be printed. The next line gives the N integers in the interval [-10000, 10000] to be inserted into an initially empty small top heap. The last line gives the M subscripts.

Output format:

For each subscript given in the input, ioutput H[i]the data on the path from the root node in one line. The numbers are separated by 1 space, and there must be no extra spaces at the end of the line.

Input sample:

5 3
46 23 26 24 10
5 4 3

Sample output:

24 23 10
46 23 10
26 10
 
 
code
 
 

#include<stdio.h>
#include<stdlib.h>

#define max 1005
#define min -10001

void Create();
void Insert( int temp);
int h[max],size;

int main()
{
int n,m;
int temp;
int i,j;

scanf("%d %d",&n,&m);
Create();
for( i=0; i<n; i++){
scanf("%d",&temp);
Insert(temp);
}

for( i=0; i<m; i++){
scanf("%d",&j);
printf("%d",h[j]);
while( j>1 ){
j /= 2;
printf(" %d",h[j]);
}
printf("\n");
}
return 0;size = 0;//Initialize heap{void Create()
}





h[0] = min; //There is no data in position 0, set the sentry
}

void Insert( int temp)
{
//Insert nodes to form a small top heap
int i;

for( i=++size; h[i/2 ]>temp;i/=2){
//Small top heap, if the parent node is greater than the insertion node, the two are exchanged
h[i] = h[i/2];
}
h[i] =temp;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324786540&siteId=291194637