题意:
求由1、2、3和5相乘组成的数字的第1500个。
思路:
采用优先队列,求得的数插入到优先队列中,注意插入之前先判断是否已经存在,可用set判断。
代码:
#include<stdio.h>
#include<queue>
#include<set>
#include<vector>
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();
if (i == 1500) {
printf("The 1500'th ugly number is %d.\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;
}