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

来源:互联网 发布:山东广电网络集团吧 编辑:程序博客网 时间:2024/06/06 01:22

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 areseparated 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

提交代码

————————————————

这个题目和云课堂上面讲的一样的。

主要涉及的知识点为。

1,堆的创建——最小堆,利用数组来表示。和上面一道题很类似。下标为i 的节点的左右儿子节点的小标为2*i 和2*i+1,反过来,父亲下标为i/2.

2,插入一个节点。先放在最后面,然后和父亲比较,如果不符合的话,换。

3,索引值的理解。从1开始,在0处放上一个哨兵。最小堆上面的哨兵的值为最小值。

————————————————

代码如下。

#include <iostream>#include <stdlib.h>using namespace std;/* run this program using the console pauser or add your own getch, system("pause") or input loop */typedef struct MinHeap{int *data;int size;int cap;}* pMinHeap;pMinHeap Creat(int Size){pMinHeap h =(pMinHeap)malloc(sizeof(struct MinHeap));h->data=(int *)malloc((Size+1)*sizeof(int));h->cap=Size;h->size=0;h->data[0]=-10001;//The Max datareturn h;}void Insert(pMinHeap h, int d){if(h->size == h->cap)return;int i=++h->size;for(;h->data[i/2]>d; i/=2){h->data[i]=h->data[i/2];}h->data[i]=d;}int main(int argc, char** argv) {int N=0, M=0;pMinHeap H;cin>>N>>M;H=Creat(N);for(int i=0; i<N; i++){int tmp=0;cin>>tmp;Insert(H,tmp);}for(int i=0; i<M; i++){int index=0;cin>>index;for(int j=index; j>0; j/=2){cout<<H->data[j];j==1?cout<<endl:cout<<" ";}}return 0;}


0 0
原创粉丝点击