丑数

UVa 136 丑数

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 .

这道题的思路:一开始看的时候,就只想着用for循环做,让一个for循环从一开始往后每次自加一(死循环),另一个for循环只执行三次,分别是*2,*3和*5。然后定义一个数组将乘积的结果保存下来,再找出第1500个符合条件的数,让其输出,并终止第一个循环,程序结束。这么写肯定会超时,而且会有很多重复的数,因为一个丑数肯定不止一种组成方法。

重点来啦:
我今天学习了一些STL和一些简单的数据结构,其中有几项数据结构,我发现可以用来解决此题。分别是set和priority_queue(优先队列)

首先我们可以用set的性质帮我们做许多事情
1. set的去重性,可以帮助我们将集合里重复的元素去除
2. set还有一个性质是自动从小到大排序(这道题先不用set,用优先队列)
代码如下:

#include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#include <queue>

using namespace std;
typedef long long LL;
const int ceo[3]={2,3,5};
//为什么要写一个cmp类型体呢?
//因为优先队列的默认排序是数字越大的优先级越高
struct cmp//使优先队列的优先方式为数字越大的优先级越低
{
   bool operator ()(const LL a,const LL b)const
   {
      return a>b;
   }
};

int main()
{
   priority_queue<LL,vector<LL>,cmp>pq;
   set<LL>s;
   pq.push(1);
   s.insert(1);
   for(int i=1;;i++)
   {
      LL x=pq.top();//注意!:这里一定要用LL,不能用int,因为int贮存不下
      pq.pop();
      if(i==1500)
      {
         cout<<"The 1500'th ugly number is "<<x<<endl;
         break;
      }
      for(int j=0;j<3;j++)
      {
         LL x2=x*ceo[j];//注意!:这里一定要用LL,不能用int,因为int贮存不下
         if(!s.count(x2))//s.count(x2)是统计x2在集合s中出现的次数,而if(!s.count(x2))的作用是判断x2在集合s中出现过没有
         {
            s.insert(x2);
            pq.push(x2);
         }
      }
   }  
   return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值