zoukankan      html  css  js  c++  java
  • c++ 优先队列

    题目题解:http://blog.csdn.net/xu12110501127/article/details/9199335

    有关博客:http://www.360doc.com/content/10/1118/16/963301_70454649.shtml 优先队列不错的博客。

    priority_queue 对于基本类型的使用方法相对简单。
    他的模板声明带有三个参数,priority_queue<Type, Container, Functional>
    Type 为数据类型, Container 为保存数据的容器,Functional 为元素比较方式。
    Container 必须是用数组实现的容器,比如 vector, deque 但不能用 list.
    STL里面默认用的是 vector. 比较方式默认用 operator< ,

     所以如果你把后面俩个
    参数 缺省的话,优先队列就是大顶堆,队头元素最大。

     

    如果要用到小顶堆,则一般要把模板的三个参数都带进去。
    STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆
    例子:

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <queue>
     4 #include <vector>
     5 #include <algorithm>
     6 #define LL long long
     7 using namespace std;
     8 
     9 struct node
    10 {
    11     int x, y;
    12     bool operator < (const node &tmp)const
    13     {
    14         return x > tmp.x;
    15     }
    16 };
    17 int main()
    18 {
    19     priority_queue<int>q1;  //基本类型从大到小
    20     priority_queue<int, vector<int>, greater<int> >q2;  //基本类型从小到大
    21     priority_queue<node>q3;  //自定义类型
    22     return 0;
    23 }

     示例:

     1 struct node 
     2 {
     3   int x, y;
     4   bool operator < (const node &tmp)const
     5   {
     6     return x > tmp.x;
     7   }
     8 };
     9 
    10 int main()
    11 {
    12   priority_queue<node>q;  //定义
    13   node no;
    14   int n, i;
    15   while(cin>>n)
    16   {
    17     for(i = 0; i < n; i++)
    18     {
    19       cin>>no.x>>no.y;  //插入结构体
    20       q.push(no);
    21     }
    22     while(n--)
    23     {
    24        cout<<(q.top()).x<<" "<<(q.top()).y<<endl;  //输出
    25        q.pop();
    26     }
    27   }
    28   return 0;
    29 }
  • 相关阅读:
    vim使用技巧
    排序
    2020-3-27 学习面向对象的笔记
    小圆圈第三章答案
    内置函数部分用法
    Pycharm快捷键
    小猿圈第二章答案
    Typora学习笔记
    AI的真实感
    Unity 横版2D移动跳跃问题——关于一段跳与二段跳
  • 原文地址:https://www.cnblogs.com/bfshm/p/3161694.html
Copyright © 2011-2022 走看看