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算法进行优化(因为优先队列首先是堆)。

  • 相关阅读:
    使用iScroll时,input等不能输入内容的解决方法
    用jquery 写的类似微博发布的效果
    jq 中each的用法 (share)
    Android SDK 安装中组件的离线安装方法 (share)
    HTML5开发手机应用viewport的作用
    Android开发环境搭建及配置phoneGap
    flipsnap手机屏幕水平滑动框架
    解读网站PR值
    文档碎片
    解读SEO 黑帽白帽 (share)
  • 原文地址:https://www.cnblogs.com/dreamzj/p/14624505.html
Copyright © 2011-2022 走看看