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.
堆的建立基础操作
非常简单 建议看看mooc何老师的视频 就明白了 这里就不再赘述了
只是我的代码不知道为何 有两个节点时间超限 希望大家能帮忙看看
1 #include <stdio.h> 2 3 void heapAdjust(int a[],int data); 4 main() 5 { 6 int i,*a,n,m,k,data; 7 scanf("%d%d",&n,&m); 8 a=malloc(n*sizeof(int)); 9 a[0]=-10001; 10 for(i=1;i<=n;i++) 11 { 12 scanf("%d",&data); 13 heapAdjust(a,data); 14 } 15 16 for(i=1;i<=m;i++) 17 { 18 scanf("%d",&k); 19 printf("%d",a[k]); 20 k=k/2; 21 while(1) 22 { 23 printf(" %d",a[k]); 24 if(k==1) 25 break; 26 k=k/2; 27 } 28 printf("\n"); 29 } 30 free(a); 31 } 32 void heapAdjust(int a[],int data) 33 { 34 static int size=0; 35 int i; 36 i=++size; 37 for(;a[i/2]>data;i=i/2) 38 a[i]=a[i/2]; 39 a[i]=data; 40 }
时间: 2024-10-13 19:55:27