1. 程式人生 > >算法入門經典-第五章 例題5-7 醜數

算法入門經典-第五章 例題5-7 醜數

space names logs ins 是否 判斷 pop spa esp

#include<iostream>
#include<vector>
#include<queue>
#include<set>
using namespace std;
typedef long long ll;
const int coeff= {2,3,5};
int main()
{
    //一些常見的優先隊列,STL提供了更為簡單的定義方法
    //對於任意醜數x 則 2x,3x,5x也是醜數,判斷一個醜數是否生成過 
    //每次取出最小的醜數,生成3個新的醜數 
    priority_queue<LL,vector<LL>,greater<LL> > pq;
    
set<LL> s; pq.push(1); s.insert(1); for(int i=1;; i++) { LL x=pq.top(); pq.pop();//序列 if(i==1500) { cout<<"The 1500th ugly number is"<<x<<".\n"; break; } for(int j=0; j<3; j++) { LL x2
=x*coeff[j]; if(!s.count(x2)) { s.insert(x2); pq.push(x1); } } return 0; }

算法入門經典-第五章 例題5-7 醜數