MOOC数据结构课程 题集12 堆中的路径

05-树7 堆中的路径 (25 分)

将一系列给定数字插入一个初始为空的小顶堆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 <iostream>
#define Tree int

using namespace std;

int find_path(Tree BHTree[], int X, Tree path[]);
void AdjustUp_minheap(Tree BHTree[], int pos);

int main()
{
	int N, M;
	cin >> N >> M;
	Tree *BHTree = new Tree[N];
	for (int i = 1; i <= N; i++)
	{
		cin >> BHTree[i];
		AdjustUp_minheap(BHTree, i);
	}

	int index, num;
	Tree *path = new Tree[N];
	bool flag = 1;
	for (int i = 0; i < M; i++)	//寻找路径, 然后输出
	{
		cin >> index;
		num = find_path(BHTree, index, path);
		if (flag)
			flag = 0;
		else
			cout << endl;
		for (int i = 0; i < num - 1; i++)
			cout << path[i] << " ";
		cout << path[num - 1];	//最后一个无空格
	}

	return 0;
}

void AdjustUp_minheap(Tree BHTree[], int pos)
{
	if (pos == 1) return;
	int parent, child;
	int minitem = BHTree[pos];

	for (child = pos; child != 1; child = parent) {
		parent = child / 2;
		if (minitem < BHTree[parent])
			BHTree[child] = BHTree[parent];
		else
			break;
	}
	BHTree[child] = minitem;
}

int find_path(Tree BHTree[], int index, Tree path[])
{
	int k = 0;
	for (Tree i = index; i > 0; i /= 2)
		path[k++] = BHTree[i];
	return k;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值