This work is entirely in accordance with gourd painting scoop, referring to the cloud classroom "data Structure" (http://mooc.study.163.com/learn/ZJU-1000033001#/learn/content) in the He Chinming teacher courseware on the construction of the heap and inserted content, Plus a dwarfish function I wrote (4 parameters passed), OK! The design requirements and code implementation are as follows
1 /*2 Name:3 Copyright:4 Author:5 DATE:05/04/15 19:346 Description:7 Insert A sequence of given numbers into an initially empty min-heap H. Then for any given index I, you is supposed to print the path from H[i "to the root.8 9 Input Specification:Ten One Each input file contains the one test case. The first line gives positive integers N and M (<=1000) which is the size of the input sequence, an d The number of indices to be checked, respectively. Given in the next line is the N integers in [ -10000, 10000] which is supposed to being inserted into an initially empty min -heap. Finally in the last line, M indices is given. A - Output Specification: - the for each index i in the input, print on one line the numbers visited along the path from h[i] to the root of the heap. The numbers is separated by a space, and there must is no extra space at the end of the line. - - Sample Input: - 5 3 + Ten - 5 4 3 + Sample Output: A Ten at Ten - Ten - */ - -#include <stdio.h> -#include <stdlib.h> in - #defineMinData-10001 to +typedefstructheapstruct - { the int*Elements; * intSize; $ intcapacity;Panax Notoginseng} *minheap; - theMinheap Create (intMaxSize); + voidInsert (Minheap H,intitem); A voidPrint (Minheap H,intAintNintM); the + intMain () - { $ //freopen ("In.txt", "R", stdin);//For Test $ intN, M, I, item; - minheap H; - thescanf"%d%d", &n, &M); - WuyiH =Create (N); the for(i =0; i < N; i++) - { Wuscanf"%d", &item); - Insert (H, item); About } $ - intA[m]; - - for(i =0; i < M; i++) Ascanf"%d", &a[i]); + the Print (H, A, N, M); - //fclose (stdin);//For Test $ return 0; the } the theMinheap Create (intMaxSize) the { -Minheap H = (minheap)malloc(sizeof(structheapstruct)); inH->elements = (int*)malloc((MaxSize +1) *sizeof(int)); theH->size =0; theH->capacity =MaxSize; Abouth->elements[0] =Mindata; the the returnH; the } + - voidInsert (Minheap H,intItem) the {Bayi inti; the thei = ++h->Size; - for(; H->elements[i/2] > item; I/=2) -H->elements[i] = h->elements[i/2]; theH->elements[i] =item; the } the the voidPrint (Minheap H,intAintNintM) - { the inti; the the for(i =0; i < M; i++)94 { the if(A[i] <=N) the { the while(A[i])98 { Aboutprintf"%d", h->Elements[a[i]]); - if(A[i] >1)101printf" ");102 Else103printf"\ n");104A[i]/=2; the }106 }107 }108}
PAT 05-Tree 6 Path in a Heap