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.
Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers N and M (<=1000) which are the size of the input sequence, and the number of indices to be checked, respectively. Given in the next line are the N integers in [-10000, 10000] which are supposed to be inserted into an initially empty min-heap. Finally in the last line, M indices are given.
Output Specification:
For each index i in the input, print in one line the numbers visited along the path from H[i] to the root of the heap. The numbers are separated by a space, and there must be no extra space at the end of the line.
Sample Input:5 3
46 23 26 24 10
5 4 3
Sample Output:24 23 10
46 23 10
26 10
这题属于二叉堆的练手题,开始以为二叉堆很难。 。结果发现还是比AVL和CBT容易一些。coding不到半小时就AC了。 。好久没有这么痛快了。
#include<stdio.h>
int IsFull(int n,int i);
void Insert(int* p,int k,int i);
int main(){
int m,n,i,k;
scanf("%d%d",&m,&n);
int heap[m+1];
heap[0] = -20000;
// 构建heap
for(i = 1;i<=m;i++){
scanf("%d",&k);
if(1 == i)
heap[i] = k;
else{
if(IsFull(m,i-1))
break;
else
Insert(heap,k,i);
}
}
// 读取,输出
for(i = 0;i<n;i++){
scanf("%d",&k);
for(int j = k;j;j/=2){
if(j == k)
printf("%d",heap[j]);
else
printf(" %d",heap[j]);
}
if(i!=n-1)
printf("\n");
}
return 0;
}
void Insert(int* p,int k,int i){
for(;p[i/2]>k;i/=2)
p[i] = p[i/2];
p[i] = k;
}
int IsFull(int n,int i){
if(n == i)
return 1;
return 0;
}