只包含质因数2, 3, 5的数称为丑数,1是第一个丑数。
将1放入优先队列,模拟生成未重复的丑数放入优先队列,小的丑数优先取出。
#include <cstdio>
#include <queue>
#include <vector>
#include <set>
using namespace std;
typedef long long LL;
const int coeff[3] = {2, 3, 5};
struct cmp {
bool operator() (const LL a, const LL b) const {
return a > b;
}
};
int main() {
priority_queue<LL, vector<LL>, cmp> pq; // 数值小的优先出队
// priority_queue<LL, vector<LL>, greater<LL> > pq;
pq.push(1);
set<LL> s;
s.insert(1);
for (int i = 1; ; ++i) {
LL x = pq.top();
pq.pop();
if (i == 1500) {
printf("The 1500'th ugly number is %lld.\n", x);
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;
}