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数据类型。
又因为集合中的元素本来就是有序的,所以此题可以不使用优先队列,直接用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;
}
每次要取队列中最小的数来生成后面的数(为了统计已生成的数的个数),但队列中的元素并不是按照大小顺序排列的,所以要用到优先队列: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;
}
相关文章推荐
- 【例题5-7 UVA - 136】Ugly Numbers
- UVA-136 Ugly Numbers
- UVA 136 Ugly Numbers
- Ugly Numbers, UVa 136
- UVa 136 - Ugly Numbers
- UVA - 136 Ugly Numbers
- UVA 136 Ugly Numbers
- UVa_136 - Ugly Numbers
- UVa 136 - Ugly Numbers
- 算法竞赛入门经典第五章例题5-7 Ugly Numbers UVA - 136
- UVA136--Ugly Numbers
- STL-UVA136-Ugly Numbers
- UVa 136 - Ugly Numbers
- Uva - 136 - Ugly Numbers
- UVA 136 Ugly Numbers
- UVA136-Ugly Numbers
- Uva - 136 - Ugly Numbers
- Uva 136 - Ugly Numbers
- UVA - 136 Ugly Numbers
- 【UVa 136】Ugly Numbers