zoukankan      html  css  js  c++  java
  • 丑数 UVA 136

    丑数是指不能被除了2,3,5以外的其他素数整数的数,把丑数从小到大排列起来,结果如下: 

    1,2,3,4,5,6,8,9,10,12,15...

    我们要求第1500个丑数。

    思考:我们可以要从小到大生成各个丑数,那么怎么生成。

    这里用到set容器和queue 优先队列

    set容器用于去重

    queue用于存放丑数

    对于一个丑数x,2x,3x,5x,也是丑数,这样可以用一个优先队列保存已生成的丑数,每次取出最小丑数,生成3个丑数。

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<string>
    #include<queue>
    #include<set>
    #include<vector>
    #include<math.h>
    using namespace std;
    typedef long long LL;
    const int coeff[3]={2,3,5};
    int main(){
        LL a,b;
        priority_queue<LL,vector<LL>,greater<LL> > p;
        set<LL> s;
        s.insert(1);
        p.push(1);
      for(int j=1;;j++)  {
            a=p.top();
            p.pop();
            if(j==1500){
                printf("The 1500'th ugly number is %d.
    ",a);
                break;
            }
           for(int i=0;i<3;i++){
            b=a*coeff[i];
            if(!s.count(b)){
                s.insert(b);
                p.push(b);
            }
           }
    
    
    
        }
    
      return 0;
    }
  • 相关阅读:
    MongoDB ObjectId
    MongoDB固定集合
    MongoDB 正则表达式
    MongoDB Map Reduce
    MongoDB操作
    VIM跳到指定行
    linux之echo命令
    rpm and yum commands
    CentOS 7 下的软件安装建议
    apt系统中sources.list文件的解析
  • 原文地址:https://www.cnblogs.com/wintersong/p/5055145.html
Copyright © 2011-2022 走看看