Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ... shows the first 11 ugly numbers. By convention, 1 is included. Write a program to find and print the 1500’th ugly number.
Input
There is no input to this program.
Output
Output should consist of a single line as shown below, with ‘’ replaced by the number computed.
Sample Output
The 1500'th ugly number is <...>.(<...>为你找到的第1500个丑数)
题意翻译
丑数是指不能被2,3,5以外的其他素数整除的数。把丑数从小到大排起来,结果如下:
1,2,3,4,5,6,8,9,10,12,15...
求第1500个丑数。
题解
不解释,直接上代码!!!
#include<cstdio>
int main(){
printf("The 1500'th ugly number is 859963392.\n");
return 0;
}
(以上内容纯属虚构。。。。)
优先队列
优先队列具有队列的所有特性,包括基本操作,只是在这基础上添加了内部的一个排序,它本质是一个堆实现的,它和queue
不同的就在于我们可以自定义其中数据的优先级, 让优先级高的排在队列前面,优先出队
定义:priority_queue<Type, Container, Functional>
Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式,当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆。
//升序队列
priority_queue <int,vector<int>,greater<int> > q;
//降序队列
priority_queue <int,vector<int>,less<int> >q;
//greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)
优先队列解法
本题的实现方法有很多种,可以从小到大生成各个丑数。最小的丑数是1,而对于任意丑数,x,2x,3x,5x也是丑数。这样,就可以用一个优先队列保存所有已生成的丑数,每次取出最小的丑数,生成3个新的丑数。唯一需要注意的是,同一个丑数有多种生成方式,所以需要判断一个丑数是否已经生成过。
#include<iostream>
#include<vector>
#include<queue>
#include<set>
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){
cout<<"The 1500'th ugly number is "<<x<<".\n";
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;
}
其他解法
#include<cstdio>
using namespace std;
const int N=1505;
int s[N]={1};
int min(int a, int b, int c){
if(a<b){
return a<c?a:c;
}else{
return b<c?b:c;
}
}
void init(){
int f2=2,f3=3,f5=5,i2=0,i3=0,i5=0;
int i=1;
while(i<N){
s[i] = min(f2,f3,f5);
if(s[i]==f2){
f2 = s[++i2]*2;
}
if(s[i]==f3){
f3 = s[++i3]*3;
}
if(s[i]==f5){
f5=s[++i5]*5;
}
i++;
}
}
int main(){
init();
printf("The 1500'th ugly number is %lld.\n",s[1500-1]);
return 0;
}