您的位置:首页 > 其它

UVa 136 Ugly Numbers

2016-10-17 13:05 330 查看
实现方法:从小到大生成各个丑数。(对于任意丑数x,2x、3x和5x都是丑数)

每次要取队列中最小的数来生成后面的数(为了统计已生成的数的个数),但队列中的元素并不是按照大小顺序排列的,所以要用到优先队列:priority_queue<int, vector<int>, greater<int> >。每一次用过x生成三个数之后就将x出队。

注意:需要使用long long数据类型。

#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<set>
using namespace std;

typedef long long LL;
set<int> s;
const int a[3]={2, 3, 5};

int main()
{
priority_queue<LL, vector<LL>, greater<LL> > pq;
pq.push(1);
s.insert(1);
for (int i=1; i<=1500; 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 * a[j];
if(!s.count(x2)) {s.insert(x2); pq.push(x2);}
//利用set来判重。此处如果用bool数组,显然太浪费空间。
}
}

return 0;
}


又因为集合中的元素本来就是有序的,所以此题可以不使用优先队列,直接用set来实现。

#include<iostream>
#include<cstdio>
#include<set>
using namespace std;

typedef long long LL;
int a[3]={2,3,5};

int main()
{
set<LL> s;
s.insert(1);

for (int i=1; i<=1500; i++) {
LL x = *s.begin(); //因为s.begin()相当于指针,所以要加*
s.erase(s.begin()); //集合中元素的删除操作,注意括号里面的是一个位置
if (i == 1500) {
printf("The 1500'th ugly number is %d.\n",x);
break;
}
for (int j=0; j<3; j++) {
LL x2 = x * a[j];
if (!s.count(x2)) s.insert(x2);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: