• 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 }
  • 相关阅读:
    是否完全二叉搜索树 (30 分)
    链表去重
    关于堆的判断
    玩转二叉树
    hdu-2795 Billboard(线段树)
    线段树超级大模版
    博弈dp 以I Love this Game! POJ
    kuangbin 最小生成树
    Infinite Maze CodeForces
    Alice’s Stamps HDU
  • 原文地址:https://www.cnblogs.com/huoxiayu/p/4423270.html
Copyright © 2020-2023  润新知