zoukankan      html  css  js  c++  java
  • 最小堆

    如下:

    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 }
    keep moving...
  • 相关阅读:
    c++异常处理
    循环数比较
    交错01串
    六一儿童节
    独立的小易
    牛客网上的最后一位
    微微信.NET 为什么採用文件系统而不是数据库?
    Ugly Numbers(1.5.8)
    xcode6-beta下载
    接收socket数据的粘包处理
  • 原文地址:https://www.cnblogs.com/xxx0624/p/2978482.html
Copyright © 2011-2022 走看看