POJ 1338 Ugly Number 优先队列

Description

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.
Given the integer n,write a program to find and print the n’th ugly number.
Input

Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.
Output

For each line, output the n’th ugly number .:Don’t deal with the line with n=0.
Sample Input

1
2
9
0
Sample Output

1
2
10
Source

New Zealand 1990 Division I,UVA 136

注意:1最小的丑数是1,而对于任意丑数x,2x,3x,5x也都是丑数。
2.只是为了熟悉一下优先队列的用法 如果是UVa 136只输出1500个数,队列和集合即可 如果是poj1338 那么还需要一个数组,方便取任意一个。
3.greater由STL提供了简单的定义方法,表示”越小的数优先级越大“
4.注意优先队列最后的两个> >不要写在一起,有很多(不是所有)编译器会误认为是”>>”运算符。

#include<iostream>
using namespace std;;
#include<queue>
#include<set>
#include<vector>
typedef long long LL;
int yinzi[3]={2,3,5};

int main()
{
    int n;
    int num[1501];
    priority_queue<LL,vector<LL>,greater<LL> > pq;//用来按照优先级存取数据 
    set<LL> s;//为了保证数据不重复
    pq.push(1);
    s.insert(1);
    num[1] = 1;
    for(int i = 1;i<=1500;i++)
    {
        LL x1 = pq.top();
        pq.pop();
        num[i] = x1;
        for(int j = 0;j<3;j++)
        {
            LL x2 = x1 * yinzi[j];
            if(!s.count(x2))//集合中不会重复插入,但是为了保证优先队列中也没有重复元素,还是要进行判断。 
            {
                s.insert(x2);
                pq.push(x2);
            }
        }   
    } 
    while(cin>>n&&n)
    {
        cout<<num[n]<<endl;
    }
    return 0;

}

更简单的办法:

#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
int main()
{
    int n;
    LL a[1501]={1};
    int i=0,j=0,k=0;
    int m = 1;
    for(;m<1500;)
    {
        a[m++]=min(a[i]*2,min(a[j]*3,a[k]*5));
        //确定一个丑数x,那么2x 3x 5x 都是丑数,i,j,k保证每个数都分别乘2 3 5,(i对应的数要乘二,j对应的数要乘三等等)每次取最小之后,相应的下标就往后移动一位,使下一个数乘2 3或者5 
        if(a[m-1]== a[i]*2) i++;
        if(a[m-1]==a[j]*3) j++;
        if(a[m-1]==a[k]*5) k++; 
    }
    while(cin>>n&&n)
     cout<<a[n-1]<<endl;
    return 0;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值