例题5-7 丑数(Ugly Numbers,UVa 136)

本文介绍了一种使用priority_queue和set数据结构来寻找第1500个丑数的方法。丑数定义为只包含质因数2、3和5的正整数。文章提供了两种实现思路的代码示例,一种利用了优先队列,另一种则直接使用集合。

原题链接:https://vjudge.net/problem/UVA-136
分类:<priority_queue>
备注:priority_queue的使用

紫书上的分析:对于任意丑数x,2x,3x,5x也都是丑数。

即使通过运算得到了1500个数,第1500个数也可能不是正好的第1500个丑数,可能是更大的数。所以要从小往大数,这样应用priority_queue就需要greater。

(作者的priority_queue(经改动))代码如下:

#include<cstdio>
#include<vector>
#include<queue>
#include<set>
using namespace std;
typedef long long ll;
int main(void)
{
	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)
		{
			printf("The 1500'th ugly number is %lld.\n", x);
			break;
		}
		ll x1 = 2 * x, x2 = 3 * x, x3 = 5 * x;
		if (!s.count(x1)) s.insert(x1), pq.push(x1); 
		if (!s.count(x2)) s.insert(x2), pq.push(x2);
		if (!s.count(x3)) s.insert(x3), pq.push(x3);
	}
	return 0;
}

这里是我自己的方法:

#include<cstdio>
#include<set>
using namespace std;
int main(void)
{
	set<long long>s;
	int cnt = 0;
	s.insert(1);
	for (set<long long>::iterator it = s.begin();; ++it)
	{
		cnt++;
		if (cnt == 1500) { printf("The 1500'th ugly number is %lld.\n", *it); break; }
		s.insert(*it * 2);
		s.insert(*it * 3);
		s.insert(*it * 5);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JILIN.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值