UVa136 Ugly Numbers (priority_queue)

来源:互联网 发布:360数据恢复大师免费版 编辑:程序博客网 时间:2024/05/08 14:40

priority_queue的个人博客常用用法:
typedef long long LL;

priority_queue<LL,vector<LL>,greater<LL> >pq;       //第一个参数是队列的类型,第二个参数是该队列的底层实现,第三个就是优先级。

priority_queue<LL,vector<LL>,less<LL> >pq;   // greater优先级的队列是先出最小值,less优先级的队列是先出最大值。

 

思路:先由最小的丑数,分别乘2,3,5,然后将新生成的丑数存入队列,然后再从队列中找出最小数重复上述步骤(ps:需要判断一个丑数是否已经生成过),重复1500次,然后取出队列中最小值,即第1500个丑数。

代码如下:

#include <iostream>
#include <vector>
#include <queue>
#include <set>
using namespace std;
typedef long long LL;
const int coeff[3]={2,3,5};
int main()
{
priority_queue<LL,vector<LL>,greater<LL> > pq; //数小的优先级越高的队列
set 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*coeff[j];
if(!s.count(x2)) { s.insert(x2); pq.push(x2); }
}
}
return 0;
}


文/洪学林个人博客

来历:洪学林个人博客模板,转发请保存出处和连接!

本文链接:http://www.hongxuelin.com/?p=126


0 0