priority_queue优先队列,插入进去的元素都会从大到小排好序
PS:在priority_queue<ll, vector<ll>, greater<ll> > pq;
中
第一个参数为数据类型,第二个参数为保存数据的容器(默认为vector<int>
),第三个参数为元素比较函数(默认为less)。//默认算子为less,即小的往前排,大的往后排(出队时序列尾的元素出队)
struct cmp { operator bool ()(int x, int y) { return x > y; // x小的优先级高 //也可以写成其他方式,如: return p[x] > p[y];表示p[i]小的优先级高}
};
priority_queue<int, vector<int>, cmp>q; //定义方法
//其中,第二个参数为容器类型。第三个参数为比较函数。
优先队列试图将两个元素x和y代入比较运算符(对less算子,调用x<y,
对greater算子,调用x>y
),若结果为真,则x排在y前面,y将先于x出队,反之,则将y排在x前面,x将先出队。
STL里面默认用的是 vector. 比较方式默认用 operator< , 所以如果你把后面俩个参数缺省的话,优先队列就是大顶堆,队头元素最大。
基本操作:
empty() 如果队列为空返回真
pop() 删除队顶元素
push() 加入一个元素
size() 返回优先队列中拥有的元素个数
top() 返回优先队列队顶元素(队列中的front()变成了top())
在默认的优先队列中,优先级高的先出队。在默认的int型中先出队的为较大的数。
例子
UVA136 - Ugly Numbers
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, …
shows the first 11 ugly numbers. By convention, 1 is included.
Write a program to find and print the 1500’th ugly number.
Input
There is no input to this program.
Output
Output should consist of a single line as shown below, with ‘’ replaced by the number
computed.
Sample Output
The 1500’th ugly number is <number>
/*
丑数就是所有是2或3或5倍数的数。
用优先队列从小到大排列丑数
用set集合判断丑数是否重复
*/#include <iostream>
#include <vector>
#include <queue>
#include <set>
using namespace std;
typedef long long LL;
const int coeff[3]={2,3,5}; int main(){/*PS:在priority_queue<ll, vector<ll>, greater<ll> > pq;中第一个参数为数据类型,第二个参数为保存数据的容器(默认为vector<int>),第三个参数为元素比较函数(默认为less)。*/ priority_queue<LL,vector<LL>,greater<LL> > pq;set<LL> s;pq.push(1);s.insert(1);for(int i=1;;i++){//pq存的第一个数的2,3,5倍找出存到set和pq里并删除pq第一个数,直至第1500个数 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*coeff[j];if(!s.count(x2)){s.insert(x2);pq.push(x2);}}}return 0;
}