UVA136

来源:互联网 发布:js日历 编辑:程序博客网 时间:2024/06/05 01:37

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

Explanation

本题为优先队列的简单例题 题目大意介绍Ugly Numbers是指不能被2,3,5以外的其他素数整除的数。 把Ugly Numbers排序后得到1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, …
求第1500个ugly number. 我们可以从小到大生成各个Ugly Number.
第一个是1,那么2、3、5也是,即对一个 Ugly Number X来说,
2*X,3*X,5*X也为Ugly Number. 需要注意的是,同一个Ugly Number有多重生成方式,那么我们需要考虑出现次数的问题.


这里用到了优先队列(priority queue)这一数据结构

普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (first in, largest out)的行为特征,即允许类似于“急诊病人插队”这样的事件发生。

Code

#include <iostream>#include <queue>#include <vector>#include <set>using namespace std;const int coeff[3] = {2, 3, 5}; //Ugly Number的扩展倍数typedef long long LL;int main(){    priority_queue<LL, vector<LL>, greater<LL> > pq;    //定义优先队列,greater可以实现越小的整数优先级越大    set<LL> s;    //因为要考虑Ugly Number的形成方式多样性,我们用到了set保证唯一次数    pq.push(1);    s.insert(1);    //起始Ugly Number为1    for(int i = 1; ; i++){        LL x = pq.top(); pq.pop();        //由于要取出优先级最高的所以要用top()而不是front()        //cout << "i " << i <<" "<< x << endl;        if(i == 1500){            cout << "The 1500'th ugly number is "<< x << "." << endl;            break;        }        for(int j = 0; j < 3; j++){            LL y = x * coeff[j];            if(!s.count(y)){                s.insert(y);                pq.push(y);            }        }    }    return 0;}
原创粉丝点击