1. 程式人生 > 實用技巧 >uva136醜數(優先佇列法)

uva136醜數(優先佇列法)

題目

醜數指不能被2,3,5整除的數。求生粗排列的第1500個醜數

預備知識:

set物件的insert()不去重,count()可以統計出現次數

程式碼:

#include <iostream>
#include<vector>
#include<queue>
#include<set>
using namespace std;
typedef long long LL;//定義一個longlong型別的數LL
const int coeff[3] = { 2,3,5 };
int main()
{
    priority_queue<LL, vector<LL>, greater<LL> >pq;//升序放無重複的醜數
    set<LL> s;//s用來判斷這個醜數有沒有出現過。注意set的insert()不去重,count()可以統計出現次數
    pq.push(1);//最小的醜數是1
    s.insert(1);
    for (int i = 1;;i++) {
        LL x = pq.top();
        pq.pop();
        if (i == 1500) {
            cout << "The 1500'th 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(x2);
            }
        }
    }
    return 0;
}