优先队列的强大在于自动排序。引用优先队列
使用优先队列需使用头文件
#include<queue>
using namespace std;
基本格式
priority_queue<数据类型> 队列名称;
最常用的为
priority_queue<node> pq;//node为结构体,而且结构体中重载了"<"
priority_quque<int,vector<int>,greater<int> >;
//不需要#include<vector>头文件
//注意后面两个“>”不要写在一起,“>>”是右移运算符 需要空格隔开
priority_queue <int,vector<int>,less<int> >q;
优先队列的基本操作
q.size();//返回q里元素个数
q.empty();//返回q是否为空,空则返回1,否则返回0
q.push(k);//在q的末尾插入k
q.pop();//删掉q的第一个元素
q.top();//返回q的第一个元素
q.back();//返回q的末尾元素
默认排序(非结构体,最简单的形式)
priority_queue<int> q;
若在此队列中插入 4 5 6 2 12 54
则输出为 54 12 6 5 4 2(顺序是由大到小)
结构体排序(结构体内部重载小于)
先观察此结构体
struct node
{
int x,y;
bool operator < (const node & a) const
{
return x<a.x;
}
};
这个node结构体有两个成员,x和y,它的小于规则是x小者小。
再来看看验证程序:
#include<cstdio>
#include<queue>
using namespace std;
struct node
{
int x,y;
bool operator < (const node & a) const
{
return x<a.x;
}
}k;
priority_queue <node> q;
int main()
{
k.x=10,k.y=100; q.push(k);
k.x=12,k.y=60; q.push(k);
k.x=14,k.y=40; q.push(k);
k.x=6,k.y=80; q.push(k);
k.x=8,k.y=20; q.push(k);
while(!q.empty())
{
node m=q.top(); q.pop();
printf("(%d,%d) ",m.x,m.y);
}
}
程序大意就是插入(10,100),(12,60),(14,40),(6,20),(8,20)这五个node。
再来看看它的输出:
(14,40) (12,60) (10,100) (8,20) (6,80)
它也是按照重载后的小于规则,从大到小排序的。
less和greater优先队列
priority_queue <int,vector<int>,less<int> > p;
priority_queue <int,vector<int>,greater<int> > q;
结论 less是从大到小,greater是从小到大
下来看看AC代码
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
#include <vector>
using namespace std;
typedef long long ll;
const int con[3] = {2,3,5};
int main(){
priority_queue<ll,vector<ll>,greater<ll> > pq;
set<ll> s;
pq.push(1);
s.insert(1);
for(int i=1; ;i++){
ll x = pq.top();
pq.pop();
if(i==1500){
cout<<"The 1500'th ugly number is "<< x <<".\n";
break;
}
for(int j=0;j<3;j++){
ll x2 = x*con[j];
if(!s.count(x2)) {
pq.push(x2);
s.insert(x2);
}
}
}
return 0;
}