POJ 1338 Ugly Numbers(丑数)

本文介绍了一种使用优先队列和集合法高效求解第N个丑数的方法。丑数是指只包含质因数2、3和5的正整数。文章详细解释了算法原理,并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.问题分析

首先啊。。。。这种题在有了大致的思路了以后就不要再照着书去实现了,真的就没什么意思了》》但就这个问题本身而言还是蛮有意思的嘛,用到了集合法对元素进行判重,其实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;
  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值