题目链接:https://cn.vjudge.net/problem/UVA-136

题意:如果一个数的因子只由2,3,5,组成,则这个数被称为丑数。按照惯例,1也被称为丑数。求第1500个丑数并·输出。

这道题没有数据输入。

思路:题意很简单,但一不小心就会超时。。。。。(但也有收获)。

      为了节省时间,我们可以用优先队列来做。但你用什么来标记一个数出现过了呢。数组吗,存不下,自己试一下就知道了大笑

所以呢,可以用map映照容器来实现这一功能,而且默认为0(只起标记作用)。

代码如下:.

#include<stdio.h>
#include<vector>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long LL;
int a[4]= {2,3,5};
int main()
{
    priority_queue<LL,vector<LL>,greater<LL> >pq;//从小到大排序
    map<LL,int>s;
    s[1]=1;
    pq.push(1);
    int sum=1;
    LL ans;
    while(sum<1500)
    {
        ans=pq.top();
        pq.pop();
        for(int i=0; i<3; i++)
        {
            if(s[ans*a[i]]==0)
            {
               s[ans*a[i]]=1;
               pq.push(ans*a[i]);  //自动按照要求排序
            }
        }
        sum++;
    }
   printf("The 1500'th ugly number is %d.\n",pq.top());
   return 0;
}

懒人代码:

#include<stdio.h>
int main()
{
    /* long long int i=0;
     long long int sum=0;
     while(1)
     {
         i++;
         int ans=i;
         while(ans%2==0)
             ans/=2;
         while(ans%3==0)
             ans/=3;
         while(ans%5==0)
             ans/=5;
         if(ans==1)
             sum++;
         if(sum==1500)
         {
             printf("%d\n",i);  //虽然超时,但出现了后面的正确结果
             break;
         }
     }*/
    printf("The 1500'th ugly number is %d.\n",859963392);//直接输出结果,多省事,哈哈哈~~~
    return 0;
}


posted on 2017-11-07 20:17  zitian246  阅读(83)  评论(0编辑  收藏  举报