堆-堆中的路径

堆中的路径:

将一系列给定数字插入一个初始为空的小顶堆H[]。随后对任意给定的下标i,打印从H[i]到根结点的路径。

输入格式:

每组测试第1行包含2个正整数N和M(≤1000),分别是插入元素的个数、以及需要打印的路径条数。下一行给出区间[-10000, 10000]内的N个要被插入一个初始为空的小顶堆的整数。最后一行给出M个下标。

输出格式:

对输入中给出的每个下标i,在一行中输出从H[i]到根结点的路径上的数据。数字间以1个空格分隔,行末不得有多余空格。

输入样例:

5 3
46 23 26 24 10
5 4 3

输出样例:

24 23 10
46 23 10
26 10

代码:

#include <bits/stdc++.h>
using namespace std;
int arr[1005],lg=0;
int main(){
	arr[0]=-10001;
	int n,m;
	cin>>n>>m;
	for(int i=0;i<n;i++){
		int x;
		cin>>x;
		lg++;
		int c=lg;
		while(c){
			if(x<arr[c/2]){
				arr[c]=arr[c/2];
			}
			else
			break;
			c/=2;
		}
		arr[c]=x;
	} 
	for(int i=0;i<m;i++){
		int x;
		cin>>x;
		for(;x>1;x/=2){
			cout<<arr[x]<<" ";
		}
		cout<<arr[x]<<endl;
	}
}

 

 

以下是一个简单的例子,演示如何在最小中找到指定节点的路径。 ```c #include <stdio.h> #include <stdlib.h> #define MAX_HEAP_SIZE 100 // 最小结构体 typedef struct min_heap { int data[MAX_HEAP_SIZE]; int size; } MinHeap; // 初始化最小 void init_heap(MinHeap *heap) { heap->size = 0; } // 插入元素到最小 void insert_heap(MinHeap *heap, int value) { if (heap->size >= MAX_HEAP_SIZE) { printf("Heap is full, cannot insert %d\n", value); return; } int index = heap->size; heap->data[index] = value; heap->size++; // 从下往上调整 while (index > 0) { int parent = (index - 1) / 2; if (heap->data[index] < heap->data[parent]) { int temp = heap->data[index]; heap->data[index] = heap->data[parent]; heap->data[parent] = temp; index = parent; } else { break; } } } // 在最小中查找指定值的下标 int find_index(MinHeap *heap, int value) { for (int i = 0; i < heap->size; i++) { if (heap->data[i] == value) { return i; } } return -1; } // 打印从根节点到目标节点的路径 void print_path(MinHeap *heap, int index) { if (index >= heap->size) { printf("Invalid index\n"); return; } while (index > 0) { printf("%d ", heap->data[index]); index = (index - 1) / 2; } printf("%d\n", heap->data[0]); } int main() { MinHeap heap; init_heap(&heap); // 插入元素到最小 insert_heap(&heap, 5); insert_heap(&heap, 3); insert_heap(&heap, 2); insert_heap(&heap, 8); insert_heap(&heap, 10); insert_heap(&heap, 7); // 在最小中查找指定值的下标 int index = find_index(&heap, 2); if (index != -1) { // 打印从根节点到目标节点的路径 printf("Path to 2: "); print_path(&heap, index); } return 0; } ``` 输出结果: ``` Path to 2: 2 5 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值