题目大意:
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, …
shows the first 10 ugly numbers. By convention, 1 is included.
把只含有2.3.5因数的数称为丑数,默认第一个丑数是1。
POJ是有多次询问,输出第n个丑数
UVA是询问第1500个丑数是多少。
思路:
利用STL的优先队列,创建一个小数优先的优先队列,然后每次取队头,分别乘以2.3.5,利用map看是否被放入过队列。从而得到按照大小顺序排列的丑数。
代码:
UVA
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
ll num=1;
priority_queue<ll,vector<ll>,greater<ll> > q;//小数优先的优先队列
map<ll,ll> mp;
int x[3]={2,3,5},cnt=1;
q.push(num);
mp[num]++;
while(!q.empty())
{
num=q.top();
q.pop();
if(cnt==1500){
cout<<"The 1500'th ugly number is "<<num<<"."<<endl;
break;
}
for(int i=0;i<3;++i){
ll a=num*x[i];
if(mp[a]==0){//对取过的丑数进行标记
q.push(a);
mp[a]++;
}
}
cnt++;
}
return 0;
}
POJ
#include<iostream>
#include<cstdlib>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
typedef long long ll;
int main()
{
ios::sync_with_stdio(false);
ll num=1;
ll ugly[1510];//打表存数,对于询问直接输出
priority_queue<ll,vector<ll>,greater<ll> > q;
map<ll,ll> mp;
int x[3]={2,3,5},cnt=1;
q.push(num);
mp[num]++;
while(!q.empty())
{
num=q.top();
q.pop();
ugly[cnt]=num;
if(cnt==1500)
break;
for(int i=0;i<3;++i){
ll a=num*x[i];
if(mp[a]==0){
q.push(a);
mp[a]++;
}
}
cnt++;
}
int n;
while(cin>>n&&n)
cout<<ugly[n]<<endl;
return 0;
}