05-树6. Path in a Heap (25)
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 3Sample Output:
24 23 10 46 23 10 26 10
最小堆,是完全二叉树的结构,且每个元素的值不大于其子节点的元素值。
#include<iostream>
using namespace std;
struct HeapStruct{
int *data;
int size;
int capacity;
};
HeapStruct *Create(int maxsize) //创建最小堆
{
HeapStruct *H=new HeapStruct;
H->data=new int[maxsize+1];
H->size=0;
H->capacity=maxsize;
H->data[0]=-10001;
return H;
}
void Insert(HeapStruct *H,int item) //将元素插入堆中
{
int i;
if(H->size == H->capacity){
return;
}
i=++H->size; //不能码成H->size++...T_T
for(;H->data[i/2]>item;i/=2){
H->data[i]=H->data[i/2];
}
H->data[i]=item;
}
int main()
{
int i,N,M;
cin>>N>>M;
HeapStruct *MinHeap=Create(N);
for(i=0;i<N;i++){
int num;
cin>>num;
Insert(MinHeap,num);
}
int c[M];
for(i=0;i<M;i++)
cin>>c[i];
for(i=0;i<M;i++){
int index=c[i];
while(index>0){
cout<<MinHeap->data[index];
if(index>1)
cout<<" ";
index/=2;
}
cout<<endl;
}
return 0;
}