堆中的路径
将一系列给定数字插入一个初始为空的小顶堆H[]。随后对任意给定的下标"i",打印从H[i]到根结点的路径。
输入样例:
5 3
46 23 26 24 10
5 4 3
输出样例:
24 23 10
46 23 10
26 10
#include<iostream>
#include<malloc.h>
const int MinData = -100000; // 哨兵值
const int MaxSize = 1005; // 最大个数
using namespace std;
typedef struct HeapStruct* Heap;
struct HeapStruct {
int* data; // 存值的数组
int size; // 当前元素个数
int capacity; // 最大容量
};
// 初始化堆
Heap Create() {
Heap H;
H = (Heap)malloc(sizeof(struct HeapStruct));
H->data = (int*)malloc(sizeof(int) * (MaxSize + 1));
H->size = 0;
H->capacity = MaxSize;
H->data[0] = MinData;
return H;
}
// 插入
void Insert(Heap H, int x) {
int i = ++H->size; // 指向数组最后一个
for (;H->data[i / 2] > x;i /= 2)
H->data[i] = H->data[i / 2];
H->data[i] = x;
}
int main() {
Heap H;
H = Create();
int n,m ,j;
cin >> n>> m;
for (int i = 0;i < n;i++) {
int t;
cin >> t;
Insert(H, t);
}
for (int i = 0;i < m;i++)
{
cin >> j;
cout << H->data[j]<<" ";
while (j > 1)
{
j /= 2;
cout << H->data[j]<<" ";
}
cout << endl;
}
return 0;
}