05-树7 堆中的路径 (25 分) C++实现
#题目
将一系列给定数字插入一个初始为空的小顶堆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
#C++代码
#include<iostream> using namespace std; #define CAPACITY 10000 #define MINDATA -10000 typedef struct Stack Stack; struct Stack { int* H; int size; int capacity; }; //Stack* creatstack(int N) //{ // Stack* stack = new Stack; // stack->capacity = CAPACITY; // stack->size = 0; // stack->H = new int[CAPACITY] {0}; // stack->H[0] = MINDATA; // int num = 0; // for (int i = 1; i <= N; i++) // { // cin >> num; // stack->H[++stack->size] = num; // } // return stack; //} //int max(int a, int b) //{ // return a > b ? a : b; //} //void sort(Stack* stack) //{ // for (int i = stack->size / 2; i; i--) // { // int child = 2 * i; // if ((child + 1) <= stack->size && stack->H[child + 1] < stack->H[child]) // child += 1; // if (stack->H[child] < stack->H[i]) // { // int temp = stack->H[i]; // stack->H[i] = stack->H[child]; // stack->H[child] = temp; // if ((child * 2 <= stack->size && stack->H[child * 2] < temp) || ((child * 2 + 1) <= stack->size && stack->H[child * 2 + 1] < temp)) // i = child + 1; // } // } //} //bool IsFull(Stack* stack) //{ // if (stack) // { // if (stack->size >= stack->capacity - 1) // return true; // else // return false; // } // else // return false; //} void insert(Stack* &stack,int num) { int i = ++stack->size; for (; stack->H[i / 2] > num; i /= 2) stack->H[i] = stack->H[i / 2]; stack->H[i] = num; } int main() { int N = 0, M = 0; cin >> N >> M; int k = 0; Stack* stack = NULL; stack = new Stack; stack->capacity = CAPACITY; stack->size = 0; stack->H = new int[CAPACITY] {0}; stack->H[0] = MINDATA; for (int i = 1; i <= N; i++) { cin >> k; insert(stack, k); } //sort(stack); for (int i = 0; i < M; i++) { //int k = 0; cin >> k; for (int j = k; j > 0; j /= 2) { cout << stack->H[j]; if (j != 1) cout << " "; } if(i<M-1) cout << endl; } system("pause"); return 0; }