uvaoj-136:ugly number

来源:互联网 发布:一年级毕业季网络直播 编辑:程序博客网 时间:2024/06/05 04:46

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 and Output

There is noinput to this program.  Output should consist of a single line asshown below, with <number> replaced by the number computed.

Sample output

The 1500'th ugly number is <number>.


answer:859963392;


题解:刘汝佳白书120页例题5-7;本题考察的重点在于优先队列的使用,也就是priority_queue;

因为合数都能由素数组成,所以这里合数不考虑;

思路就是进行循环,让这三个数互相乘,每次取最小的数,这样进行1500次就行了;

这里面的集合的作用主要是判断某一个数是否曾经出现过,因为同一个数可能会多次产生;

详细代码如下:


code:

#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <queue>
using namespace std;
const int base[3]={2,3,5};

int main()
{
    priority_queue<long long, vector<long long >,greater<long long > > pq;
    set<long long > s;
    s.clear();
    s.insert(1);
    pq.push(1);
    for(int i=1; ; i++)
    {
        long long x=pq.top();
        pq.pop();
        if(i==1500)
        cout<<"The 1500'th ugly number is " <<x<<".\n";
        for(int j=0; j<3; j++)
        {
            long long temp=x*base[j];
            if(!s.count(temp))
            {
                s.insert(temp);
                pq.push(temp);
            }
        }
    }
    return 0;
}

笔记:
priority_queue< int , vector<int> , greater<int> > pq;
其中的三个函数分别指队列类型,容器类型,优先级条件;



0 0
原创粉丝点击