紫书5-7
题目链接
思路
从小到大生成丑数,如果数x是丑数,那么2x,3x,5x也是丑数,所以我们将已生成的丑数保存在优先队列,每次取最小的丑数,让其生成三个丑数,需要注意,如果生成的丑数已经生成过便不可再生成,由于priority_queue无法使用count函数的(count函数是关联容器所有的,而prority_queue是由顺序容器vector实现的),所以引用了set。
代码
有关greater可以参看此博客,有关priority_queue可以参看此博客
#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<LL> s;
pq.push(1);
s.insert(1);
for(int i=1;;i++)
{
LL x=pq.top();
pq.pop();
//第1500个
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];
//如果x2不在s中
if(!s.count(x2))
{
s.insert(x2);
pq.push(x2);
}
}
}
return 0;
}