丑数(优先队列)

《算法竞赛入门经典》刘汝佳 5-7   丑数  P120

题目:

丑数是指不能被除了2,3,5以外的其他素数整数的数,把丑数从小到大排列起来,结果如下: 

                                                     1,2,3,4,5,6,8,9,10,12,15

我们要求第1500个丑数。

分析:

example:

第一次:1

第二次:1    2    3    5(将1乘以2,3,5)(同理再将上述数字乘以2,3,5)(重复的数字舍去)

第三次:1

                2    4    6    10

                3    6    9     15

                5    10  15    25

               整理为:1,2,3,4,5,6,9,10,15,25

    1、首先每次都是取最小的数,分别乘以2,3,5。所以使用vector或者priority_queue。都行。

    2、为了省空间,前面被乘的数可以删除。上面两者都可以。vector.pop_back(),priority_queue.pop()

          这里使用priority_queue<LL,vector<LL>,greater<LL> >pq;

    3、为了去除相同的数字可以使用map或者set。但这里是集合的概念,用set更好。

思路:

    从operate>的优先队列中,取对头元素,乘以2,3,5。

     判断集合中是否有相同的元素。如果没有,放入集合,放入优先队列。

    重复上述操作1500次。

代码:

#include<iostream>
#include<queue>
#include<vector>
#include<functional>//greater头文件 
#include<set>
#include<algorithm>//count函数 
using namespace std;

typedef long long LL;

int main() 
{
	const int ugly[3]={2,3,5};
	priority_queue<LL,vector<LL>,greater<LL> >pq;
	set<LL>s;
	pq.push(1);
	int i,j;
	LL x,nextns;
	for(i=1;;i++)
	{
		x=pq.top();
		if(i==1500)
			cout<<"The 1500'th ugly number is"<<x<<endl;
		s.insert(x);
		pq.pop();
		for(j=0;j<3;j++)
		{
			nextns=x*ugly[j]; 
			if(!s.count(nextns))
			{
				s.insert(nextns);
				pq.push(nextns);
			}
		}
	}
	return 0;
}

  

备注: 

3、优先输出大数据 priority_queue Type为数据类型, Container为保存数据的容器,Functional为元素比较方式。 如果不写后两个参数,那么容器默认用的是vector,比较方式默认用operator<,也就是优先队列是大顶堆,队头元素最大。 --------------------- 本文来自 小拳头 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/xiaoquantouer/article/details/52015928?utm_source=copy

参考文章:

【c++】STL里的priority_queue用法总结

greater<int>()和less<int>()的使用

猜你喜欢

转载自blog.csdn.net/sinat_38816924/article/details/82823545