题意:丑数是不能被2,3,5以外的其他素数整除的数,求第1500个丑数
1.对于任意丑数,它的2x,3x,5x都是丑数
2.这里用一个优先队列(值越小优先级越高的)来计算并存储丑数
3.注意不同的丑数可能新产生的丑数相同,所以我们用一个集合来维护队列元素唯一性
PS:这个题目还有个有趣的地方是可以直接打印答案(也就是说你只要知道第1500个丑数是什么就可以AC,即使你写不出这个代码)
以下是刘汝佳老师(做了点小改动以及添加了注释)的代码:
#include <iostream>
#include <set>
#include <queue>
#define LL long long
using namespace std;
//这里的greater表示优先队列的规则,值越小的优先级越大
priority_queue<LL, vector<LL>,greater<LL> > pq;
//集合具有元素唯一性.其他特性这里用不到
set<LL> s;
int main()
{
pq.push(1);
int number=1;
while(number<1500) //此循环执行1499次
{
number++;
LL t=pq.top(); //取优先队列队首元素(即最小值)
pq.pop(); //队首出列,更新队首元素
//队首的倍数在集合中找不到时才把这个数压进队列,以及加入集合
if(!s.count(t*2)){pq.push(t*2);s.insert(t*2);}
if(!s.count(t*3)){pq.push(t*3);s.insert(t*3);}
if(!s.count(t*5)){pq.push(t*5);s.insert(t*5);}
}
//已经有1499个队首出列了,那么接下来这个队首就是第1500个丑数了
cout << "The 1500'th ugly number is " << pq.top() << ".\n";
return 0;
}
直接打印答案版本:
#include <iostream>
int main()
{
std::cout << "The 1500'th ugly number is " << 859963392 << ".\n";
return 0;
}