poj - 1338 - Ugly Numbers(優先隊列)

來源:互聯網
上載者:User

標籤:blog   http   io   ar   sp   2014   on   log   amp   

題意:問第n(n <= 1500)小的醜數(質因數只有2或3或5)是幾。

題目連結:http://poj.org/problem?id=1338

——>>1, 2, 3, 4, 5, 6, 8, ...

假設小根堆存以上醜數,那麼每次取出最小的數,這個最小的數nMin,它可以產生三個數:nMin * 2, nMin * 3, nMin * 5,將這三個數放入小根堆繼續,一直複篩出1500個醜數為止。

小根堆可用優先隊列來替代。

#include <cstdio>#include <queue>#include <vector>using std::priority_queue;using std::vector;using std::greater;const int MAXN = 1500;long long nRet[MAXN];void GetUglyNumbers(){    int nCnt = 0;    priority_queue<long long, vector<long long>, greater<long long> > pq;    pq.push(1);    while (nCnt < MAXN)    {        long long nMin = pq.top();        pq.pop();        if (nRet[nCnt] != nMin)        {            nRet[++nCnt] = nMin;            pq.push(nMin * 2);            pq.push(nMin * 3);            pq.push(nMin * 5);        }    }}int main(){    int n;    GetUglyNumbers();    while (scanf("%d", &n) == 1 && n)    {        printf("%I64d\n", nRet[n]);    }    return 0;}


poj - 1338 - Ugly Numbers(優先隊列)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.