将一系列给定数字插入一个初始为空的小顶堆H[]。随后对任意给定的下标i,打印从H[i]到根结点的路径。
输入格式:
每组测试第1行包含2个正整数N和M(≤1000),分别是插入元素的个数、以及需要打印的路径条数。下一行给出区间[-10000, 10000]内的N个要被插入一个初始为空的小顶堆的整数。最后一行给出M个下标。
输出格式:
对输入中给出的每个下标i,在一行中输出从H[i]到根结点的路径上的数据。数字间以1个空格分隔,行末不得有多余空格。
输入样例:
5 3
46 23 26 24 10
5 4 3
输出样例:
24 23 10
46 23 10
26 10
#include <bits/stdc++.h>
using namespace std;
struct Node{
int *s;
int size;
int maxn_size;
};
typedef Node *MinHeap;
MinHeap create(int Maxn){
MinHeap h=(MinHeap)malloc(sizeof(Node));
h->s=(int*)malloc((Maxn+1)*sizeof(int));
h->size=0;
h->maxn_size=Maxn;
h->s[0]=-100001;//哨兵
return h;
}
void insert(MinHeap h,int t){
if(h->size==h->maxn_size){
cout<<"最小堆已满"<<endl;
return;
}
int i=++h->size;
for(;t<h->s[i/2];i/=2){
h->s[i]=h->s[i/2];
}
h->s[i]=t;
}
void print(MinHeap h,int t){
if(t>h->size){
cout<<"ERROR"<<endl;
return;
}
for(int i=t;t>0;t/=2){
if(i!=t)cout<<" ";
cout<<h->s[t];
}
}
int main()
{
int n,m;
int t;
cin>>n>>m;
MinHeap h=create(n);
for(int i=1;i<=n;i++){
cin>>t;
insert(h,t);
}
for(int i=0;i<m;i++){
cin>>t;
print(h,t);
cout<<endl;
}
return 0;
}