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
<pre name="code" class="cpp">/*2015.7.12cyq*/
#include <iostream>
#include <vector>
using namespace std;
void adjustDown(vector<int> &a,int root,int n){//将root结点的树调为小根堆,此操作的前提是root的子树都是小根堆
a[0]=a[root];//a[0]暂存root
for(int i=2*root;i<=n;i*=2){
if(i<n&&a[i]>a[i+1])
i++; //较小的子结点
if(a[0]<=a[i]) //不能再往下走了
break;
else{//将左右小根堆子树中较小的结点上移,根结点下移root=i,继续对其左右子树操作
a[root]=a[i];
root=i;
}
}
a[root]=a[0]; //填坑
}
void buildMinHeap(vector<int> &a,int n){
for(int i=n/2;i>0;i--)
adjustDown(a,i,n);
}
int main(){
int N,M;
cin>>N>>M;
vector<int> a(N+1); //舍弃a[0],将其用作辅助变量,便于层序编码,a[i]的左子树为a[2*i],右子树为a[2*i+1];
for(int i=1;i<=N;i++){
cin>>a[i];
buildMinHeap(a,i);
}
while(M--){
int i;
cin>>i;
while(i>1){
cout<<a[i]<<" ";
i=i/2;
}
cout<<a[1]<<endl;
}
return 0;
}