码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-25 12:25:48      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:浙大pat   mooc   c语言实现      

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 3
46 23 26 24 10
5 4 3
Sample 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://www.patest.cn/contests/mooc-ds/04-%E6%A0%919

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:浙大pat   mooc   c语言实现      

原文地址:http://blog.csdn.net/ice_camel/article/details/47054519

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!