POJ 2247 Humble Numbers

题目传送门: http://poj.org/problem?id=2247
题意:一个数,若其质因子只有2,3,5,7,那么称这个数为丑数。1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27。为前20个丑数。编写一个程序打印第n个丑数。
解题方法:暴力+set
解题思路:刚一开始是想用优先队列打个表,后来发现用优先队列会有重复的元素,而且在遍历的时候不太方便实现。故改为用set实现。打表时是将集合中的每一个元素都乘以2,3,5,7再加入集合中,利用set会自动从小到大排序和无重复元素的性质,进行实现。
注意事项:
    1.打表时数据范围要稍大一些,虽然题目中给的数据范围最大到5842,但是只计算到5842或5900时,样例中最后一组数据的结果会有误。(本人开到了10000)
    2.iterator不能直接进行+n操作(指针可以),需利用advance函数将迭代器移位(了解了~~~)
    3.注意输出格式。(英文有一些些麻烦)
代码: 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
#include <algorithm>
using namespace std;
set <long long> num;
int dir[4]={2,3,5,7};
int main()
{
	set <long long>::iterator iter1;
	set <long long>::iterator iter2;
	num.insert(1);
	iter1=num.begin();
	iter2=num.begin();
	//cout<<*iter1<<endl;
	while(num.size()<=10000)
	{
		for(int j=0;j<4;j++)//每一个元素都乘以2,3,5,7,再入队 
		{
			num.insert((*iter1)*dir[j]);
			//cout<<(*iter1)*dir[j]<<endl;
		}
		iter1++;	
	}
	int n;
	while(cin>>n&&n)
	{
		advance(iter2,n-1);
		if(n%10==1&&n%100!=11)
		cout<<"The "<<n<<"st humble number is "<<(*iter2)<<"."<<endl;
		else if(n%10==2&&n%100!=12)
		cout<<"The "<<n<<"nd humble number is "<<(*iter2)<<"."<<endl;
		else if(n%10==3&&n%100!=13)
		cout<<"The "<<n<<"rd humble number is "<<(*iter2)<<"."<<endl;
		else
		cout<<"The "<<n<<"th humble number is "<<(*iter2)<<"."<<endl;
		iter2=num.begin();
	}
	return 0;
} 


猜你喜欢

转载自blog.csdn.net/qq_41279172/article/details/80598008