最小堆

如下:

heapify每次把当前分支的最小的放在top

然后遍历每个“小树”,即可。。

View Code
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 using namespace std;
 5 const int maxn = 100005;
 6 #define LEFT( x ) ((x<<1)+1)
 7 #define RIGHT( x ) ((x+1)<<1)
 8 #define PARENT( x ) ((x-1)/2)//((x+1)>>1-1)
 9 int a[ maxn ];
10 void heapify( int pos,int n ){
11     int pos_l,pos_r,tmp;
12     pos_l = LEFT( pos );
13     pos_r = RIGHT( pos );
14     tmp = pos;
15     if( pos_l<=n&&a[ pos_l ]<a[ pos ] ){
16         tmp = pos_l;
17     }
18     if( pos_r<=n&&a[ pos_r ]<a[ tmp ] ){
19         tmp = pos_r;
20     }//GET THE MIN
21     if( tmp!=pos ){
22         swap( a[ tmp ],a[ pos ] );
23         heapify( tmp,n );
24     }
25     return ;
26 }
27 
28 int build_the_min_top( int n ){
29     for( int i=(int)PARENT( n );i>=0;i-- ){
30         heapify( i,n );
31     }
32     return a[ 0 ];//return the min
33 }
34 
35 int main(){
36     int ca;
37     scanf("%d",&ca);
38     for( int t=0;t<ca;t++ ){
39         int num;
40         scanf("%d",&num);
41         printf("case #%d:\n",t);
42         int n = 0;
43         while( num-- ){
44             char s[5];
45             scanf("%s",s);
46             if( s[0]=='B' ){
47                 int tmp;
48                 scanf("%d",&tmp);
49                 a[ n++ ] = tmp;
50             }
51             else {
52                 printf("%d\n",build_the_min_top( n-1 ) );
53                 swap( a[ 0 ],a[ n-1 ] );
54                 n--;//remove the min to the tail
55             }
56         }
57     }
58     return 0;
59 }

 

转载于:https://www.cnblogs.com/xxx0624/archive/2013/03/24/2978482.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值