您的位置:首页 > 其它

uva 136(Ugly Numbers, 优先队列基础)

2015-09-20 15:53 351 查看
题目大意:

丑数是指不能被2, 3, 5以外的其他素数整除的数。把丑数从小到大排列起来,结果如下:

1, 2, 3, 4, 5, 6, 9, 10, 12, 15.......

求第15000个丑数的值;

题目分析:

从小到大生成丑数,怎么生成呢,设x是丑数,2*x, 3*x, 5*x依然是丑数, 因为1是丑数,所以我们可以通过2*x, 3*x, 5*x得到所有的丑数;证明呢, 可以通过素数分解证明吧(我不是很清楚)

怎么依次得到丑数呢? 将所生成的丑数加入到优先队列中(注意一个丑数可能有不同的生成方法,需要判重);

参考代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <set>

using namespace std;

typedef long long LL;
set<LL> s;
priority_queue<LL, vector<LL>, greater<LL> > pq;
int mul[3] = {2, 3, 5};

void Init(){
while(!pq.empty())
pq.pop();
s.clear();
}

int main()
{
Init();
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 %lld.\n", x);
break;
}
LL mx;
for(int i = 0; i < 3; ++i){
mx = x*mul[i];
if(!s.count(mx)){
s.insert(mx);
pq.push(mx);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: