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

    priority_queue又称优先队列,其底层用堆来进行实现。在优先队列中,队首元素一定是当前队列中优先级最高的那一个。

    用处:当作最大,最小堆来使用,免去堆的一系列复杂操作。

    一、priority_queue的定义

    添加头文件#include<queue>,并在头文件下面加上“using namespace std;”

    二、访问

    #include<bits/stdc++.h>
    using namespace std;
    #define inf 0x3fffffff
    const int maxn=1010;
    int main(){
        priority_queue<int> q;
        q.push(3);
        q.push(4);
        q.push(1);
        printf("%d
    ",q.top());
        return 0;
    }

    三、常用函数实例

    (1)push()

    push(x)将x入队,时间复杂度为O(logN),N为元素个数

    (2)top()

    top()可以获得队首元素(即堆顶元素),时间复杂度为O(1)

    (3)pop()

    pop() 令队首元素(即堆顶元素)出队,时间复杂度为O(logN)

    实例:

    #include<bits/stdc++.h>
    using namespace std;
    #define inf 0x3fffffff
    const int maxn=1010;
    int main(){
        priority_queue<int> q;
        q.push(3);
        q.push(4);
        q.push(1);
        printf("%d
    ",q.top());
        q.pop();
        printf("%d
    ",q.top());
        return 0;
    }

    (4)empty()

    empty()检测优先队列是否为空,返回true则空,返回false则非空,时间复杂度O(1)

    (5)size()

    size()返回优先队列内元素个数,时间复杂度为O(1)

    四、priority_queue内元素优先级的设置

    (1)基本数据类型的优先级设置(int,double,char等)

    priority_queue(int) q;
    priority_queue(int,vector<int>,less<int> ) q;   //less<int> 表示数字大的优先级越大
    priority_queue(int,vector<int>,greater<int> ) q;    //greater<int> 表示数字小的优先级大

    (2)结构体的优先级设置

    #include<bits/stdc++.h>
    using namespace std;
    #define inf 0x3fffffff
    const int maxn=1010;
    //priority_queue(int) q;
    //priority_queue(int,vector<int>,less<int> ) q;   //less<int> 表示数字大的优先级越大
    //priority_queue(int,vector<int>,greater<int> ) q;    //greater<int> 表示数字小的优先级大
    struct fruit{
        string name;
        int price;
        friend bool operator< (fruit f1,fruit f2){    //表示f1<f2
            return f1.price<f2.price;   //表示price大的优先级高
            return f1.price>f2.price;   //表示price小的优先级高
        }
    }f1,f2,f3;
    int main(){
        priority_queue<fruit> q;
        f1.name="a";
        f1.price=1;
        f2.name="b";
        f2.price=2;
        f3.name="c";
        f3.price=3;
        q.push(f1);
        q.push(f2);
        q.push(f3);
        cout<<q.top().name<<" "<<q.top().price<<endl;
        return 0;
    }
    
    //输出:c 3

     五、常见用途:

    priority_queue可以解决一些贪心问题,也可以对dijkstra算法进行优化(因为优先队列首先是堆)。

  • 相关阅读:
    极客互动极客技术专题【003期】:java mvc 增删改查 自动生成工具来袭
    协议命令网络工程试验一
    主题网站分享两套免费的超棒响应式HTML5网站模板
    算法结点图的多源点最短路问题和传递闭包之FloydWarshall算法 By ACReaper
    属性页面Flexbox布局的简单演示之二
    数据库性能Quest Performance Analysis Overview
    网站查看帮助查看本地表单元素样子的网站 Native Form Elements
    文件格式配置文件weka频繁模式挖掘使用方法
    风格希望分享8个超棒的免费界面UI设计
    方法事务applicationContext.xml
  • 原文地址:https://www.cnblogs.com/dreamzj/p/14624505.html
Copyright © 2011-2022 走看看