UVA 136 & POJ1338 Ugly Numbers

题目链接:POJ UVA

题目大意:

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值