zoukankan      html  css  js  c++  java
  • toj 2196 优先队列和堆的用法

    很简单的优先队列或者堆的使用。

     1 #include <iostream>
     2 #include <queue>
     3 using namespace std;
     4 
     5 //greater对int来说表示值越小优先级越高,也可以自己定义比较函数
     6 priority_queue< int, vector<int>, greater<int> > q;
     7 char op[2];
     8 
     9 int main ()
    10 {
    11     int n;
    12     while ( cin >> n, n )
    13     {
    14         while ( n-- )
    15         {
    16             cin >> op;
    17             if ( op[0] == 'B' )
    18             {
    19                 int tmp;
    20                 cin >> tmp;
    21                 q.push(tmp);
    22             }
    23             else if ( op[0] == 'G' )
    24             {
    25                 cout << q.top() << endl;                
    26                 q.pop();
    27             }
    28         }
    29         while ( !q.empty() )
    30         {
    31             q.pop();
    32         }
    33     }
    34     return 0;
    35 }

     然后是堆的:

     1 //make_heap函数的用法类似下面两个函数
     2 #include <algorithm>
     3 #include <iostream>
     4 using namespace std;
     5 
     6 const int N = 100000;
     7 int heap[N];
     8 char op[2];
     9 int cnt;
    10 
    11 bool cmp( int a, int b )
    12 {
    13     return a > b;
    14 }
    15 
    16 int main ()
    17 {
    18     int n;
    19     while ( cin >> n, n )
    20     {
    21         cnt = 0;
    22         while ( n-- )
    23         {
    24             cin >> op;
    25             if ( op[0] == 'B' )
    26             {
    27                 int tmp;
    28                 cin >> tmp;
    29                 //push_heap
    30                 //注意push的用法,要先手动加入heap再调用
    31                 heap[cnt++] = tmp;
    32                 push_heap( heap, heap + cnt, cmp );
    33             }
    34             else if ( op[0] == 'G' )
    35             {
    36                 //pop_heap
    37                 //注意pop的用法,pop只是将堆顶的元素放到了heap最末尾的位置
    38                 pop_heap( heap, heap + cnt, cmp );
    39                 cnt--;
    40                 cout << heap[cnt] << endl;
    41             }
    42         }
    43     }
    44     return 0;
    45 }
  • 相关阅读:
    Visifire Chart控件设置 柱状图 条的宽窄
    silverlight+wcf 获得web参数
    Maven教程(转载)
    Eclipse插件CheckStyle的安装和使用
    log4net面面观之工作原理
    javabean实体类对象转为Map类型对象的方法(转发)
    ORACLE数据库创建用户名和表空间
    ORACLE 12C PDB 维护基础介绍
    int 与 Integer--话说数组转集合
    Shiro--权限控制
  • 原文地址:https://www.cnblogs.com/huoxiayu/p/4423270.html
Copyright © 2011-2022 走看看