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;
}