【刘汝佳书】例题5-7 UVA136 (priority_queue、set的练习)

生成数列,用priority_queue比较合适,可以保证每次取出最小的元素
判重用set合适,将出现过的元素都加入set,然后用set.count()可以判断是否在集合中
数列问题注意数据类型范围

#include <iostream>
#include <queue>
#include <set>

using namespace std;

typedef long long LL;

int main()
{
    priority_queue<LL, vector<LL>, greater<LL> > q;
    set<long long> Used;
    int x[3]={2,3,5};

    q.push(1);
    Used.insert(1);

    LL smallest;
    int cnt = 1;

    for(cnt = 1; ; cnt++){
        smallest = q.top(); q.pop();

        if(cnt == 1500) break;

        for(int i=0; i<3; i++) {
            if(!Used.count(smallest*x[i])) {
                Used.insert(smallest*x[i]);
                q.push(smallest*x[i]);
            }
        }
    }
    printf("The 1500'th ugly number is %lld.\n", smallest);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41727666/article/details/89027931