136 Ugly Numbers(priority_queue+逆向求解要求数)

题目链接:

https://cn.vjudge.net/problem/UVA-136

 1 /*问题 
 2 输出第1500个丑数,丑数的定义是不能被2,3,5以外的其他素数整除的数
 3 
 4 解题思路
 5 直接硬暴力先试一下发现枚举的时候不知道它能被那个素数整除,况且打很大的素数表依次遍历也不一定能够找到1500个丑数。
 6 那么根据定义,如果x是一个丑数,那么2*x、3*x、5*x也一定是丑数。那么构建一个优先队列,让数值小的优先级最高,加入第一个丑数1,
 7 依次加入三个丑数(数值小的在前面),直到第1500个丑数时结束,另外可能生成的丑数会重复,因此需要一个set集合来记录哪些数已经
 8 出现过了。 
 9 */
10 #include<cstdio>
11 #include<iostream>
12 #include<cmath>
13 #include<vector>
14 #include<set>
15 #include<queue> 
16 using namespace std;
17 const int m[3]={2,3,5};
18 
19 typedef long long LL;
20 
21 int main()
22 {
23     set<LL> s;
24     priority_queue<LL,vector<LL>,greater<LL> > pq;
25     
26     s.insert(1);
27     pq.push(1); 
28     for(int i=1;;i++){
29         LL x=pq.top();
30         pq.pop();
31         
32         if(i == 1500){
33             cout<<"The 1500'th ugly number is "<<x<<'.'<<endl;
34             break;
35         }
36         for(int j=0;j<3;j++){
37             LL x1=x*m[j];
38             if(!s.count(x1)){
39                 s.insert(x1);
40                 pq.push(x1);
41             }
42         }
43     }
44     return 0;    
45 } 
原文地址:https://www.cnblogs.com/wenzhixin/p/8969515.html