您的位置:首页 > 其它

UVA 136 Ugly Numbers

2018-01-11 09:39 465 查看
题意
丑数是指不能被2,3,5以外的其他素数整除的数。把丑数从小到大排列起来,结果如下:
1,2,3,4,5,6,8,9,10,12,15……
求第1500个丑数


输入
没有输入


输出
The 1500'th ugly number is n.

从小到大生成丑数,假如一个丑数为x,那么2x,3x,5x,也是丑数,那么我们可以用优先队列把生成的丑数都压入,然后每次求队列中最小丑数生成的三个丑数,然后再压入队列(当然此时可以用set判重),直到队列弹出1500次,此时恰好是第1500个丑数,复杂度很低,所以直接模拟就可以。当然其他方法也可以做,但是这种方法更好理解,由紫书提供!

#include <set>
#include <queue>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
int dx[3] = {2, 3, 5};
priority_queue<ll ,vector<ll>, greater<ll> >q;//优先队列从小到大
set<ll> Set;
int main() {
q.push(1);
Set.insert(1);
for(int i = 1; ; i++) {
ll t = q.top();
q.pop();//每一次都会弹出最小值
if(i == 1500) {
printf("The 1500'th ugly number is %d.\n",t);//当弹出1500次之后,这个值就是第1500个值
break;
}
for(int j = 0; j < 3; j++) {
ll t1 = t * dx[j];
if(Set.count(t1) == 0) {
Set.insert(t1);
q.push(t1);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: