这里综合运用了Set 和 优先队列:
整体思路:
凡是2,3,5的倍数的都是丑数,所以可以开一个优先队列(整数越小,优先级越高),先插入1,在插入用1乘以2,3,5得到2,3,5的倍数,然后把优先队列的.top去掉,不断取top直到1500个为止:
收获:常用优先队列(整数越小,优先级越高):
priority_queue<long long ,vector<long long>,greater<long long > >pq;
#include<queue>
#include<cstdio>
#include<vector>
#include<set>
using namespace std;
typedef long long ll;
int main()
{
const int cofee[] = {2,3,5};
priority_queue<ll,vector<ll>,greater<ll> >pq;//整数越小,优先级越高!
set<ll>s;
s.insert(1);
pq.push(1);
for (int i = 1; i < 1500; ++i){
ll x = pq.top();
pq.pop();
for (int j = 0; j < 3; ++j){
ll num = cofee[j] * x;
if (!s.count(num)){//之所以得检测一下num是否存在,是因为pq优先队列是不能保证元素不重复的,但又不好查找,所以直接用set查找!
s.insert(num);
pq.push(num);
}
}
}
printf("The 1500'th ugly number is %lld.\n",pq.top());
return 0;
}