丑数 简单的优先队列和set

来源:互联网 发布:软件系统集成设计方案 编辑:程序博客网 时间:2024/05/01 02:09
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
1290
Sample Output
1210
题意大概是 1个数列其中的数的质因数只能包含2,3,5问第n个这样的数是多少。
优先队列priority_queue 和set用于判断新生成的数是否重复,比如2*3=6 3*2=6
#include <cstdio>#include <cstring>#include <iostream>#include <string>#include <cmath>#include <algorithm>#include <queue>#include <stack>#include <deque>#include <vector>#include <cctype>#include <ctime>#include <map>#include <set>using namespace std;typedef long long ll;const int INF = 0x3f3f3f3f;const int dx[] = {-1, 0, 1, 0, -1, -1, 1, 1};const int dy[] = {0, 1, 0, -1, 1, -1, 1, -1};#define N 10005#define eps 1e-5#define pai acos(-1)#define MOD 1e9+7ll num[3]={2,3,5};int main(){    #ifndef ONLINE_JUDGE    freopen("in.txt","r",stdin);    ll _begin=clock();    #endif    int n;    while(scanf("%d",&n)&&n)    {        priority_queue < ll , vector<ll> ,greater<ll> > s;        set<ll> ugly;        s.push(1);        ugly.insert(1);       for(int i=1;;i++)       {           ll x=s.top(); s.pop();           if(i==n)            {                printf("%lld\n",x);                break;            }           for(int j=0;j<=2;j++)           {               ll x2=x*num[j];               if(!ugly.count(x2))               {                   s.push(x2);                   ugly.insert(x2);               }           }       }    }    #ifndef ONLINE_JUDGE    ll _end=clock();    printf("%lldms\n",_end-_begin);    #endif    return 0;}


0 0