04-树9. Path in a Heap (25)

来源:互联网 发布:手机淘宝4.0 编辑:程序博客网 时间:2024/06/05 19:16

04-树9. Path in a Heap (25)

时间限制
150 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue

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 346 23 26 24 105 4 3
Sample Output:
24 23 1046 23 1026 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://www.patest.cn/contests/mooc-ds/04-%E6%A0%919

0 0
原创粉丝点击