UVA 136 Ugly Numbers

来源:互联网 发布:linux命令手册下载chm 编辑:程序博客网 时间:2024/05/29 17:09

分析:本题主要介绍STL 中优先队列(priority queue)的运用
思路: 实现方法有多种,这里仅看一种,利用优先队列的性质,从小到大生成丑数,最小的是1,而对于丑数x,2x, 3x, 4x都是丑数。
知识点:

1.STL中的优先队列定义在头文件<queue> 中,用priority_queue<int> pq 来声明,这个pq是一个“越小的整数优先级越低的优先队列”,注意与下面代码中的区别

代码:

#include<iostream>#include<set>#include<queue>#include<vector>using namespace std;typedef long long LL;const int a[3] = {2,3,5};int main(){    //常见的优先队列“越小的整数优先级越大的整数”,STL中给出了定义的方法    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 << ".\n";            break;        }        for(int j = 0;j < 3; j++)        {            LL x2 = x * a[j];            if(!s.count(x2)) //因为一个丑数会有不同的数生成, 所以这里看是否已经存在这样一个丑数            {                s.insert(x2); //如果没有,分别把它放在集合和队列中                pq.push(x2);            }        }    }    return 0;}
0 0