PAT 数据结构 04-树9. 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 3
Sample 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;
}


 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值