queue 优先队列

eg:uva136  

题意 丑数是指不能被2 ,3 ,5 以外素数整除的数,把丑数从小到大排列如下: 1 , 2 ,3 ,5 ,6 。。。

    求第1500个丑数;

分析: 最小的丑数为1,让他进入优先队列,then  2x,3x,5x  这些都是丑数,用优先队列保存一下,然后在从队列出来,在循环。

注意:不要把已生成的丑数多次进入优先队列。可以用set保存判断就好了。

 1 #include<iostream>
 2 #include<vector>
 3 #include<queue>
 4 #include<set>
 5 using namespace std;
 6 typedef long long LL;
 7 const int coeff[3]={2,3,5};
 8 
 9 int main()
10 {
11     priority_queue<LL,vector<LL>,greater<LL> > pq;
12     set<LL> s;
13     pq.push(1);
14     s.insert(1);
15     for(int i=1; ;i++)
16     {
17         LL x=pq.top(); pq.pop();
18         if(i==1500)
19         {
20             cout << x << endl;
21         }
22         for(int j=0;j<3;j++)
23         {
24             LL x2=coeff[j]*x;
25             if(!s.count(x2)){
26                 s.insert(x2);     pq.push(x2);
27             }
28         }
29      } 
30      return 0;
31 }
View Code

 

posted on 2016-02-03 00:00  青春的梦想付诸行动  阅读(151)  评论(0编辑  收藏  举报

导航