poj Ugly Numbers(优先队列)

Ugly Numbers
原题链接: http://poj.org/problem?id=1338

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
代码示例:
 
   
#include
#include
#include
using namespace std;
#define ll long long int
ll  result[1510];
void que()
{
    ll i=0;
    priority_queue,greater >s;//优先队列优先选取较小元素
    s.push(1);
    while(i<1505)
    {
        int k=s.top();
        s.pop();
        if(i>0&&k==result[i-1])//去重
            continue;
        result[i++]=k;
        s.push(k*2);
        s.push(k*3);
        s.push(k*5);
    }
}
int main()
{
    ll n;
    que();
    while(~scanf("%lld",&n)&&n)
    {
        printf("%lld\n",result[n-1]);
    }
    return 0;
}

你可能感兴趣的:(栈/队列,ACM)