Topic link:
https://cn.vjudge.net/problem/UVA-136
1 /* Problem 2 outputs the 1500th ugly number. The definition of an ugly number is a number that cannot be divisible by other prime numbers other than 2, 3, and 5. 3 4 Problem- solving ideas 5. Try hard and violent first. You don’t know when you find the enumeration. It can be divisible by that prime number, and traversing a large prime number table in turn may not be able to find 1500 ugly numbers. 6 Then by definition, if x is an ugly number, then 2*x, 3*x, 5*x must also be ugly numbers. Then build a priority queue, let the smaller value have the highest priority, add the first ugly number 1, 7 and add three ugly numbers in turn (the smaller value is in the front), until the end of the 1500th ugly number. Ugly numbers repeat, so a set is needed to keep track of which numbers have already appeared in 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 }