UVA 136 Ugly Numbers

题意:求第1500个丑数(不能被2,3,5以外的其他素数整除的数)。

思路:从小到大生成各个丑数,最小的丑数是1,对于任意丑数x,2x,3x,5x都是丑数;

因此利用优先队列保存已经生成的丑数,每次取出最小的丑数,生成3个新的丑数;

但要注意去重,比如2,3都会生成6,于是用set来存、判断重复。

 1 //The 1500'th ugly number is<number>.
 2 #include "iostream"
 3 #include "set"
 4 #include "vector"
 5 #include "queue"
 6 #include "functional"
 7 using namespace std;
 8 typedef long long LL;
 9 int main()
10 {
11     set<LL> s;
12     priority_queue<LL, vector<LL>, greater<LL> >pq;//从小到大
13     int cof[3] = { 2,3,5 };
14     s.insert(1);
15     pq.push(1);
16     for (int i = 1;; i++)
17     {
18         LL x = pq.top();//取最小的
19         //cout << "x=" << x << endl;
20         pq.pop();
21         if (i == 1500)
22         {
23             //输出
24             cout << "The 1500'th ugly number is "<< x<< ".\n";
25             break;
26         }
27         
28         for (int j = 0; j < 3; j++)
29         {
30             LL x2;
31             x2 = x*cof[j];
32             if (!s.count(x2))//去重
33             {
34                 s.insert(x2);
35                 pq.push(x2);
36             }
37         }
38     }
39     return 0;
40 }

猜你喜欢

转载自www.cnblogs.com/fudanxi/p/10357404.html