Uva136

Ugly Numbers UVA - 136

Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...
shows the first 11 ugly numbers. By convention, 1 is included. Write a program to find and print the 1500’th ugly number. Input There is no input to this program. Output Output should consist of a single line as shown below, with ‘<number>’ replaced by the number computed. Sample Output The 1500'th ugly number is <number>.

 

 1 #include<bits/stdc++.h>
 2 #define LL long long
 3 using namespace std;
 4 const int a[3]={2,3,5};
 5 int main()
 6 {
 7     set<LL>m;
 8     priority_queue<LL,vector<LL>,greater<LL> >t;
 9     m.insert(1);
10     t.push(1);
11     for(int i=1;;i++)
12     {
13         LL n=t.top();
14         t.pop();
15         if(i==1500)
16             {printf("The 1500'th ugly number is %lld.\n",n);
17             break;
18             }
19         for(int j=0;j<3;j++)
20         {
21             LL x=1ll*a[j]*n;
22             if(!m.count(x))
23             {
24                 m.insert(x);
25                 t.push(x);
26             }
27         }
28     }
29     return 0;
30 }

思路:

用Set来判重,用优先队列来排序。排到第1500个输出。

注意点:

行尾'\n',用int会溢出。

 

此代码还可以简化,省去优先队列的操作,因为,未自定义set本身就是从小到大排列的。

 1 #include<bits/stdc++.h>
 2 #define LL long long
 3 using namespace std;
 4 const int a[3]={2,3,5};
 5 int main()
 6 {
 7     set<LL>m;
 8     set<LL>::iterator it;
 9     m.insert(1);
10     for(int i=1;;i++)
11     {
12         it=m.begin();
13         if(i==1500)
14             {printf("The 1500'th ugly number is %lld.\n",*it);
15             break;
16             }
17         for(int j=0;j<3;j++)
18             m.insert((*it)*a[j]);
19         m.erase(*it);
20     }
21     return 0;
22 }

注意点:

  m.insert((*it)*a[j]);
  m.erase(*it);

先插入元素再删除第一个元素,原因是如果先删除第一个元素,再插入的时候*it相当于指向的是原来第二小的元素,这就不对了。

posted @ 2019-05-30 17:00  zuiaimiusi  阅读(194)  评论(0编辑  收藏  举报