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;
    }
  • 相关阅读:
    高斯消元
    UVa12103
    UVa10294
    UVa11762
    牛客网算法工程师能力评估
    华为研发工程师编程题
    网易2017春招笔试真题编程题集合
    2017网易有道内推编程题
    2017网易雷火实习生招聘编程题
    数组---面试知识点整理
  • 原文地址:https://www.cnblogs.com/wintersong/p/5055145.html
Copyright © 2011-2022 走看看