UVa 136 Ugly Numbers

本文介绍了一种高效求解第1500个丑数的方法,通过使用优先队列和集合,避免了重复计算并保持了数值的唯一性。采用long long数据类型确保了大数值的正确处理。

实现方法:从小到大生成各个丑数。(对于任意丑数x,2x、3x和5x都是丑数)


每次要取队列中最小的数来生成后面的数(为了统计已生成的数的个数),但队列中的元素并不是按照大小顺序排列的,所以要用到优先队列:priority_queue<int, vector<int>, greater<int> >。每一次用过x生成三个数之后就将x出队。

注意:需要使用long long数据类型。


#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<set>
using namespace std;

typedef long long LL;
set<int> s;
const int a[3]={2, 3, 5};

int main()
{
	priority_queue<LL, vector<LL>, greater<LL> > pq;
	pq.push(1);
	s.insert(1);
	for (int i=1; i<=1500; i++) {
		LL x = pq.top();
		pq.pop();
		if (i == 1500) {
			printf("The 1500'th ugly number is %d.\n",x);
			break;
		}
		for (int j=0; j<3; j++) {
			LL x2 = x * a[j];
			if(!s.count(x2)) {s.insert(x2); pq.push(x2);}
			//利用set来判重。此处如果用bool数组,显然太浪费空间。 
		}
	}
	
	return 0;
}


又因为集合中的元素本来就是有序的,所以此题可以不使用优先队列,直接用set来实现。

#include<iostream>
#include<cstdio>
#include<set>
using namespace std;

typedef long long LL;
int a[3]={2,3,5};

int main()
{
	set<LL> s;
	s.insert(1);
	
	for (int i=1; i<=1500; i++) {
		LL x = *s.begin();  //因为s.begin()相当于指针,所以要加*
		s.erase(s.begin());  //集合中元素的删除操作,注意括号里面的是一个位置
		if (i == 1500) {
			printf("The 1500'th ugly number is %d.\n",x);
			break;
		}
		for (int j=0; j<3; j++) {
			LL x2 = x * a[j];
			if (!s.count(x2)) s.insert(x2);
		}
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值