您的位置:首页 > 其它

POJ 1338 Ugly Numbers(丑数)

2016-05-12 15:43 211 查看

一.问题分析

首先啊。。。。这种题在有了大致的思路了以后就不要再照着书去实现了,真的就没什么意思了》》但就这个问题本身而言还是蛮有意思的嘛,用到了集合法对元素进行判重,其实map也是可以实现的嘛,还有就是一开始我的想法是按照素数分解每个丑数都可以分解成为2^z*3^x*5^y,这种形式,但是一时也没找出好的方案来生成合理有序的xyz序列(其实根本就是没有动脑子吧,下次中午要好好睡觉!),最后发现如果x是丑数那么2x,3x,5x,也一定都是丑数,这样每次生成的方案就十分简单了,再利用优先队列的性质,问题很容易就解决了。

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

1210

#include <iostream>
#include <cstring>
#include <queue>
#include <set>
using namespace std;
int n;
int op[]={2,3,5};
int main()
{
//freopen("input.txt","r",stdin);
while(cin>>n)
{
if(n==0) break;
priority_queue< long long ,vector<long long>,greater<long long> > pq;
set<long long> s;
pq.push(1);
s.insert(1);
for(int i=1;i<=n;i++)
{
if(i==n) cout<<pq.top()<<endl;
else
{
long long temp=pq.top();
pq.pop();
//cout<<temp<<" ";
for(int j=0;j<3;j++)
{
//cout<<"("<<temp<<"*"<<op[j]<<")  ";
long long x;
x=temp*op[j];
if(!s.count(x))
{
pq.push(x);
s.insert(x);
}
}
}
}
}
return 0;
}



三.优先队列的注意点

注意,优先队列是队列里的元素按照一定的优先级进行排列的队列,默认的情况下是数越大优先级越大,还可以通过重写cmp函数来实现优先级大小比较的设定,但是如果希望小的数字优先级高,有种简单的方法#include <iostream>

priority_queue< long long ,vector<long long>,greater<long long> > pq;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: