PAT : 05-树6. Path in a Heap (25)

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>
#include <stdlib.h>


int main()
{
	int m, n;
	scanf("%d %d", &n, &m);
	int *node = (int *) malloc ((n+1) * sizeof(int));
	int i, p, temp, length=1;
	for(i = 0; i < n; i++)
	{
		scanf("%d", &node[length]);
		p = length++;
		while(node[p] < node[p/2] && p > 1)
		{
			temp = node[p/2];
			node[p/2] = node[p];
			node[p] = temp;


			p /= 2;
		}
	}


	for(i = 0; i < m; i++)
	{
		scanf("%d", &p);
		for(; p > 1; p /= 2)		
			printf("%d ", node[p]);			
		printf("%d\n", node[p]);
	}


	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值