解题思路:首先丑数是指不能被2,3,5以外其他素数整除的数。最小的丑数数1,对任意一个丑数x; 则2x,3x,5x也都是
丑数,一个丑数有多种生成方式,所以,每取出一个丑数都要进行判断是否已经生成过(通过set集合元素不重复的性质),还需要注意的是,本题数据应该用long long 类型存储,故自定义类型ll (typedef long long ll)。
- #include<cstdio>
- #include<set>
- #include<queue>
- using namespace std;
- typedef long long ll;
- int main(){
- priority_queue<ll ,vector<ll> ,greater<ll> >pq;
- set<ll>set1;
- int a[]={2,3,5};
- pq.push(1);
- set1.insert(1);
- int i=1;
- while(true){
- ll temp=pq.top();
- pq.pop();
- if(i==1500)
- {
- printf("The 1500'th ugly number is %lld.\n",temp);
- break;
- }
- for(int j=0;j<3;j++)
- {
- ll t=a[j]*temp;
- if(set1.count(t))continue;
- set1.insert(t);
- pq.push(t);
- }
- i++;
- }
- return 0;
- }