c++ priority_queue

Priority queue优先级队列
Priority queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains, according to some strict weak ordering criterion.

Priority queues时一种容器执行器,其中第一个元素,是容器中最大的元素,根据严格的弱序准则

This context is similar to a heap, where elements can be inserted at any moment, and only the max heap element can be retrieved (the one at the top in the priority queue).

它的结构很像一个堆,元素可以被随时插入,只有堆中最大的元素可以被取到

Priority queues are implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are popped from the “back” of the specific container, which is known as the top of the priority queue.

Priority queues被实现为一种容器适配器,它们是使用特定容器类的封装对象作为其基础容器的类,提供了一组特定的成员函数来访问其元素。元素被弹出从特定容器的“后退”,称为优先级队列的顶部。

优先队列具有队列的所有特性,包括基本操作,只是在这基础上添加了内部的一个排序,它本质是一个堆实现的

和队列基本操作相同:
-top 访问队头元素
-empty 队列是否为空
-size 返回队列内元素个数
-push 插入元素到队尾 (并排序)
-emplace 原地构造一个元素并插入队列
-pop 弹出队头元素
-swap 交换内容

定义:priority_queue<Type, Container, Functional>
Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式,当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆
一般是:

//升序队列
priority_queue <int,vector<int>,greater<int> > q;
//降序队列
priority_queue <int,vector<int>,less<int> >q;

//greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)

例题: 第几个幸运数

到x星球旅行的游客都被发给一个整数,作为游客编号。 x星的国王有个怪癖,他只喜欢数字3,5和7。
国王规定,游客的编号如果只含有因子:3,5,7,就可以获得一份奖品。

我们来看前10个幸运数字是: 3 5 7 9 15 21 25 27 35 45 因而第11个幸运数字是:49

小明领到了一个幸运数字 59084709587505,他去领奖的时候,人家要求他准确地说出这是第几个幸运数字,否则领不到奖品。

请你帮小明计算一下,59084709587505是第几个幸运数字。

需要提交的是一个整数,请不要填写任何多余内容。

这是蓝桥杯2018年省赛A组的第4题

代码

#include<iostream>
#include<vector>
#include<queue>
#include<set>
using namespace std;
typedef long long ll;
const int num[3]={3,5,7};
int main() {
    priority_queue<ll, vector<ll>, greater<ll>> q;
//set作为一个容器也是用来存储同一数据类型的数据类型,
//并且能从一个数据集合中取出数据,在set中每个元素的值都唯一,
//而且系统能根据元素的值自动进行排序。
//应该注意的是set中数元素的值不能直接被改变。
    set<ll> ans;
    ans.insert(1);
    q.push(1);
    //每次循环得到一个幸运数
    for(ll i=0;;i++){
        ll x=q.top();//访问队头元素
        q.pop();//弹出队头元素
        if(x==59084709587505){
            cout<<i<<endl;
            break;
        }
        for(int j=0;j<3;j++){
            ll x1=x*num[j];
            //count()用来判断元素在set中是否存在
            if(!ans.count(x1)){
                ans.insert(x1);
                q.push(x1);
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值