UVA - 136 Ugly Numbers (优先队列)

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>.

题意:丑数是指不能被2,3,5以外的其他素数整除的数,把丑数从小到达排,求第1500个;

可以从小到大生成各个丑数,最小的是1,而对于任意的丑数x,2x,3x,5x也是丑数,用优先队列保存所有已生成的丑数,每次取出最小的丑数,生成3个新的丑数。注意查重;

紫书,120

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <string>
#include <queue>
#include <stack>
#include <set>
using namespace std;
typedef long long ll;

const int a[3] = {2,3,5};

int main()
{
    priority_queue<ll,vector<ll>,greater<ll> >pq;
    set<ll> s;
    pq.push(1);
    s.insert(1);
    for(int i = 1; ; i++){
        ll x = pq.top();
        pq.pop();
        if(i == 1500){
            cout << "The 1500'th ugly number is " << x <<'.' << endl;
            break;
        }
        for(int j = 0;j < 3;j++){//生成3个
            ll x2 = x*a[j];
            if(!s.count(x2)){//查重
                s.insert(x2);
                pq.push(x2);
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42754600/article/details/81254406
今日推荐