题意:
定义丑数是只能被2,3,5整除的数,求第1500个丑数
思路:
利用优先队列,每次取出最小的数,并分别乘上2,3,5,并用set判断是否已经存在
代码:
#include <iostream>
#include <queue>
#include <set>
using namespace std;
typedef long long LL;
priority_queue<LL, vector<LL>,greater<LL> >Q;
set<LL>S;
int main()
{
int a[3]={2,3,5};
Q.push(1);
S.insert(1);
for(int i=1;;i++)
{
long long now=Q.top();
Q.pop();
if(i==1500)
{
cout<<"The 1500'th ugly number is "<<now<<".\n";
break;
}
for(int j=0;j<3;j++)
{
LL next=now*a[j];
if(!S.count(next))
{
S.insert(next);
Q.push(next);
}
}
}
return 0;
}