[POJ1338]Ugly Numbers
生活随笔
收集整理的這篇文章主要介紹了
[POJ1338]Ugly Numbers
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
[POJ1338]Ugly Numbers
試題描述
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, ...?
shows the first 10 ugly numbers. By convention, 1 is included.?
Given the integer n,write a program to find and print the n'th ugly number.
輸入
Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.輸出
For each line, output the n’th ugly number .:Don’t deal with the line with n=0.輸入示例
1 2 9 0輸出示例
1 2 10數(shù)據(jù)規(guī)模及約定
見“輸入”
題解
首先與處理一下前 1500 個(gè)“丑數(shù)”,建立一個(gè)堆,對于一個(gè)“丑數(shù)” x,我們把 x * 2, x * 3, x * 5 都扔進(jìn)堆,輸出一下發(fā)現(xiàn)居然沒有爆 unsigned long long(事實(shí)上連 int 都沒爆),所以就是思博題了。
查詢就訪問數(shù)組即可。
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <stack> #include <vector> #include <queue> #include <cstring> #include <string> #include <map> #include <set> using namespace std;const int BufferSize = 1 << 16; char buffer[BufferSize], *Head, *Tail; inline char Getchar() {if(Head == Tail) {int l = fread(buffer, 1, BufferSize, stdin);Tail = (Head = buffer) + l;}return *Head++; } int read() {int x = 0, f = 1; char c = Getchar();while(!isdigit(c)){ if(c == '-') f = -1; c = Getchar(); }while(isdigit(c)){ x = x * 10 + c - '0'; c = Getchar(); }return x * f; }#define maxn 1510 #define ULL unsigned long long int n; ULL num[maxn]; priority_queue <ULL> Q;int main() {num[1] = 1;Q.push(-2ll); Q.push(-3ll); Q.push(-5ll);for(int i = 2; i <= 1500; i++) {num[i] = -Q.top(); Q.pop();while(num[i] == num[i-1]) num[i] = -Q.top(), Q.pop();Q.push(-(num[i] << 1ll)); Q.push(-num[i] * 3ll); Q.push(-num[i] * 5ll);}while(1) {n = read();if(!n) break;printf("%llu\n", num[n]);}return 0; }?
轉(zhuǎn)載于:https://www.cnblogs.com/xiao-ju-ruo-xjr/p/5803054.html
總結(jié)
以上是生活随笔為你收集整理的[POJ1338]Ugly Numbers的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux下如何产生core,调试cor
- 下一篇: SPOJ 3267: DQUERY 树