uvaoj-136:ugly number

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 and Output

There is noinput to this program.  Output should consist of a single line asshown below, with <number> replaced by the number computed.

Sample output

The 1500'th ugly number is <number>.


answer:859963392;


題解:劉汝佳白書120頁例題5-7;本題考察的重點在於優先隊列的使用,也就是priority_queue;

因爲合數都能由素數組成,所以這裏合數不考慮;

思路就是進行循環,讓這三個數互相乘,每次取最小的數,這樣進行1500次就行了;

這裏面的集合的作用主要是判斷某一個數是否曾經出現過,因爲同一個數可能會多次產生;

詳細代碼如下:


code:

#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <queue>
using namespace std;
const int base[3]={2,3,5};

int main()
{
    priority_queue<long long, vector<long long >,greater<long long > > pq;
    set<long long > s;
    s.clear();
    s.insert(1);
    pq.push(1);
    for(int i=1; ; i++)
    {
        long long x=pq.top();
        pq.pop();
        if(i==1500)
        cout<<"The 1500'th ugly number is " <<x<<".\n";
        for(int j=0; j<3; j++)
        {
            long long temp=x*base[j];
            if(!s.count(temp))
            {
                s.insert(temp);
                pq.push(temp);
            }
        }
    }
    return 0;
}

筆記:
priority_queue< int , vector<int> , greater<int> > pq;
其中的三個函數分別指隊列類型,容器類型,優先級條件;



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章