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

本文介绍如何构建一个最小堆并实现从指定节点到根节点的路径查找功能。输入包括序列大小、待检查的索引数量及数值序列,输出则是从指定索引开始到根节点的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值