Ugly Numbers UVA - 136 丑数

版权声明:本文为博主原创文章,未经博主允许不得转载,欢迎添加友链。 https://blog.csdn.net/qq_42835910/article/details/88602397

题目链接

 丑数是指不能被2,3,5以外的其他素数整除的数。把丑数从小到大排列起来,结果如下:
1,2,3,4,5,6,8,9,10,12,15,…
求第1500个丑数。
【分析】
本题的实现方法有很多种,这里仅提供一种,即从小到大生成各个丑数。最小的丑数是1,而对于任意丑数x,2x、3x和5x也都是丑数。这样,就可以用一个优先队列保存所有已生成的丑数,每次取出最小的丑数,生成3个新的丑数。唯一需要注意的是,同一个丑数有多种生成方式,所以需要判断一个丑数是否已经生成过

#include <iostream>
#include <queue>
#include <set>
using namespace std;
const int N = 150;
const long long a[3] = {2,3,5};
typedef long long LL;

int main(int argc, char** argv) {
	priority_queue<LL, vector<LL>, greater<LL> > pq;
	set<LL> num;	
	pq.push(1); num.insert(1);
	for(int i = 1; ; i++){
		if(i == 1500){
			cout << "The 1500'th ugly number is " << pq.top() << ".\n"; 
			break;
		}
		int x = pq.top(); pq.pop();
		for(int j = 0; j< 3; j++){
			LL n = a[j]*x;
			if(!num.count(n)){
				num.insert(n);
				pq.push(n);
			}			
		}
	}	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42835910/article/details/88602397