堆模板

 
  1. #include <stdio.h>

  2. #include <stdlib.h>

  3. int head[500],n;

  4. void shiftdown(int note)

  5. {

  6. while(note*2<=n)//如果不存在子节点

  7. {

  8. int mi=head[note];//让最小值初始化为该节点

  9. if(mi>head[note*2])//小领堆

  10. mi=head[note*2];

  11. if(note*2+1<=n)

  12. if(mi>head[note*2+1])

  13. mi=head[note*2+1];

  14. if(mi==head[note])

  15. break;

  16. else if(mi==head[note*2])

  17. head[note*2]=head[note],head[note]=mi,note=note*2;

  18. else

  19. head[note*2+1]=head[note],head[note]=mi,note=note*2+1;

  20. }

  21. }

  22. void create_head()

  23. {

  24. for(int i=n/2; i>=1; i--)

  25. {

  26. shiftdown(i);

  27. }

  28. }

  29. int main()

  30. {

  31. scanf("%d",&n);

  32. for(int i=1; i<=n; i++)//i一定要从1开始

  33. {

  34. scanf("%d",&head[i]);

  35. }

  36. create_head();

  37. while(--n)

  38. {

  39. printf("%d\n",head[1]);

  40. head[1]=head[n+1];

  41. shiftdown(1);

  42. }

  43. printf("%d\n",head[1]);

  44. return 0;

  45. }

转自  https://blog.csdn.net/w13884794538/article/details/81669522

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值