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 3Sample Output:
24 23 10 46 23 10 26 10
#include <stdio.h> void insert(int *heap, int val) { int child = ++heap[0]; int parent = child / 2; while (parent > 0 && heap[parent] > val) { //上滤 heap[child] = heap[parent]; child = parent; parent = child / 2; } heap[child] = val; } int main() { // freopen("test.txt", "r", stdin); int n, m; scanf("%d%d", &n, &m); int heap[1000] = {}; //0位置放置堆中元素大小,1位置为堆顶 for (int i = 0; i < n; ++i) { int num; scanf("%d", &num); insert(heap, num); } while (m--) { int index; scanf("%d", &index); while (index > 0) { printf("%d", heap[index]); if (index != 1) printf(" "); index /= 2; } printf("\n"); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/ice_camel/article/details/47054519