zoukankan      html  css  js  c++  java
  • Uva136

    Ugly Numbers 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 ‘<number>’ replaced by the number computed. Sample Output The 1500'th ugly number is <number>.

     1 #include<bits/stdc++.h>
     2 #define LL long long
     3 using namespace std;
     4 const int a[3]={2,3,5};
     5 int main()
     6 {
     7     set<LL>m;
     8     priority_queue<LL,vector<LL>,greater<LL> >t;
     9     m.insert(1);
    10     t.push(1);
    11     for(int i=1;;i++)
    12     {
    13         LL n=t.top();
    14         t.pop();
    15         if(i==1500)
    16             {printf("The 1500'th ugly number is %lld.
    ",n);
    17             break;
    18             }
    19         for(int j=0;j<3;j++)
    20         {
    21             LL x=1ll*a[j]*n;
    22             if(!m.count(x))
    23             {
    24                 m.insert(x);
    25                 t.push(x);
    26             }
    27         }
    28     }
    29     return 0;
    30 }

    思路:

    用Set来判重,用优先队列来排序。排到第1500个输出。

    注意点:

    行尾' ',用int会溢出。

    此代码还可以简化,省去优先队列的操作,因为,未自定义set本身就是从小到大排列的。

     1 #include<bits/stdc++.h>
     2 #define LL long long
     3 using namespace std;
     4 const int a[3]={2,3,5};
     5 int main()
     6 {
     7     set<LL>m;
     8     set<LL>::iterator it;
     9     m.insert(1);
    10     for(int i=1;;i++)
    11     {
    12         it=m.begin();
    13         if(i==1500)
    14             {printf("The 1500'th ugly number is %lld.
    ",*it);
    15             break;
    16             }
    17         for(int j=0;j<3;j++)
    18             m.insert((*it)*a[j]);
    19         m.erase(*it);
    20     }
    21     return 0;
    22 }

    注意点:

      m.insert((*it)*a[j]);
      m.erase(*it);

    先插入元素再删除第一个元素,原因是如果先删除第一个元素,再插入的时候*it相当于指向的是原来第二小的元素,这就不对了。

  • 相关阅读:
    【WF2017】Mission Improbable
    【Codeforces 837D】Round Subset
    【Codeforces 788C】The Great Mixing
    【JSOI2008】最大数
    2.1图像的数字化
    MATLAB生成随机数
    四六级准考证号忘记了如何快速查询四六级成绩?
    加密与水印结合
    如何在 PyPI安装python的软件包?
    matlab中如何定义函数
  • 原文地址:https://www.cnblogs.com/zuiaimiusi/p/10950654.html
Copyright © 2011-2022 走看看