• Ugly Numbers(STL应用)


    Ugly Numbers
    Time Limit: 1000MS   Memory Limit: 10000K
    Total Submissions: 21920   Accepted: 9789

    Description

    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, ...
    shows the first 10 ugly numbers. By convention, 1 is included.
    Given the integer n,write a program to find and print the n'th ugly number.

    Input

    Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.

    Output

    For each line, output the n’th ugly number .:Don’t deal with the line with n=0.

    Sample Input

    1
    2
    9
    0
    

    Sample Output

    1
    2
    10
    

    Source

     
    用set 自动去除重复元素的性质,也可以用一个优先队列保存所有已生成的丑数,每次取出最小的丑数,生产3个新的丑数,因为丑数有多种生成方式所以每次要判断一个丑数是否已经生成过了
    set代码:
     1 #include<cstdio>
     2 #include<set>
     3 #include<queue>
     4 using namespace std;
     5 #define ll long long 
     6 #define N 1510
     7 set<ll> s;
     8 set<ll> :: iterator it;
     9 ll un[N];
    10 int main()
    11 {
    12     int n, c = 0;
    13     s.clear();
    14     s.insert(1);
    15     it = s.begin();
    16     while(c<1510)
    17     {
    18         ll u = *it;
    19         un[c++] = u;
    20         s.insert(2*u), s.insert(3*u), s.insert(5*u);
    21         it++;
    22     }
    23 //    for(int i = 0; i < 20; i++) printf("%lld ", un[i]); puts("");
    24     while(~scanf("%d",&n),n)
    25         printf("%lld
    ",un[n-1]);
    26     return 0 ;
    27 }

    用到优先队列的方法:

     1 #include<cstdio>
     2 #include<set>
     3 #include<queue>
     4 using namespace std;
     5 #define ll long long 
     6 #define N 1510
     7 set<ll> s;
     8 priority_queue<ll, vector<ll> ,greater<ll> > qu;
     9 ll un[N];
    10 int main()
    11 {
    12     int n;
    13     s.insert(1);
    14     qu.push(1);
    15     for(int i = 0 ; i < 1510 ; i++)
    16     {
    17         ll tm = qu.top();
    18         if(!s.count(tm*2)) { s.insert(tm*2) ; qu.push(tm*2);}
    19         if(!s.count(tm*3)) { s.insert(tm*3) ; qu.push(tm*3);}
    20         if(!s.count(tm*5)) { s.insert(tm*5) ; qu.push(tm*5);}
    21         qu.pop();
    22     }
    23     set<ll>::iterator it;
    24     int cnt = 0 ;
    25     for( it = s.begin() ; cnt < 1510; it++)//结束条件改一下  要是it<s.end() 会runtime error
    26     {
    27         un[cnt++] = (*it);
    28     }
    29 //    for(int i = 0; i < 1501; i++) printf("%lld
    ", un[i]);
    30   while(~scanf("%d",&n),n)    {
    31     printf("%lld
    ",un[n-1]);
    32     }
    33     return 0 ;
    34 }

     注意,结束条件是pop了1500次,不是s的size是1500,因为最后还会进来更小的值

  • 相关阅读:
    复制工程或修改工程名字后找不到第三方库解决方法
    描述文件不匹配的解决方法
    JSON Code3840错误
    swift介绍和语言概述
    swift
    新入行程序员应知的十个秘密
    signal SIGABRT
    属性,属性赋值及其内存管理
    HTTP网络请求
    使用类目删除可变字符串中重复字母的一个算法
  • 原文地址:https://www.cnblogs.com/shanyr/p/4738578.html
Copyright © 2020-2023  润新知